1 CSE 142 Lecture Notes Conditional Execution with if Statements; Methods that Return Values (briefly) Chapters 3 and 4 Suggested reading: 3.3-3.4; 4.4-4.9.

Slides:



Advertisements
Similar presentations
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Advertisements

BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
1 BUILDING JAVA PROGRAMS CHAPTER 4 CONDITIONAL EXECUTION.
1 Parameters. 2 Repetitive figures Consider the task of drawing the following figures: ************* ******* *********************************** **********
1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
CS305j Introduction to Computing While Loops 1 Topic 15 Indefinite Loops - While Loops "If you cannot grok [understand] the overall structure of a program.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
1 CSE 142 Lecture Notes Interactive Programs with Scanner Chapter 4 Suggested reading: Suggested self-checks: Section 4.10 #1-4 These lecture.
CS305j Introduction to Computing Conditional Execution 1 Topic 12 Conditional Execution "We flew down weekly to meet with IBM, but they thought the way.
Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Topic 12 more if/else, cumulative algorithms, printf Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 10/27/20151.
Building Java Programs
Building Java Programs Chapter 3 Parameters and Objects Copyright (c) Pearson All rights reserved.
1 if / else statements. 2 Conditionals “If you eat your vegetables, then you can have dessert.” “If you do your homework, then you may go outside to play,
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
CS305j Introduction to Computing Parameters and Methods 1 Topic 8 Parameters and Methods "We're flooding people with information. We need to feed it through.
Copyright 2008 by Pearson Education 1 The if statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; }
Copyright 2010 by Pearson Education The if/else statement reading: 4.1, 4.6.
1 Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted,
Building Java Programs
Building Java Programs Chapter 4
Building Java Programs
Math Methods that return values
Building Java Programs Chapter 4
Building Java Programs
Lecture 4: Conditionals
Topic 11 Scanner object, conditional execution
Building Java Programs
CSc 110, Spring 2017 Lecture 8: input; if/else
Building Java Programs
Building Java Programs Chapter 4
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 6: Conditionals AP Computer Science Principles
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Building Java Programs
Boolean logic suggested reading: 5.2.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Indefinite loop variations
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 – 3.4, 4.1, 4.5
Building Java Programs Chapter 4
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

1 CSE 142 Lecture Notes Conditional Execution with if Statements; Methods that Return Values (briefly) Chapters 3 and 4 Suggested reading: ; Suggested self-checks: Section 3.9 #5-7, 11-12, 18; Section 4.10 #5-23 These lecture notes are copyright (C) Marty Stepp May not be rehosted, copied, sold, or modified without Marty Stepp's expressed written permission. All rights reserved.

2 Conditional Execution The if statement The if/else statement

3 The if statement Programs that read user input often want to take different actions depending on the values of the user's input. if statement: A Java statement that executes a block of statements only if a certain condition is true. If the condition is not true, the block of statements is skipped. General syntax: if ( ) { ; } Example: int gpa = console.nextDouble(); if (gpa <= 2.0) { System.out.println("Your application is denied."); }

4 The if/else statement if/else statement: A Java statement that executes one block of statements if a certain condition is true, and a second block of statements if the condition is not true. General syntax: if ( ) { ; } else { ; } Example: int gpa = console.nextDouble(); if (gpa <= 2.0) { System.out.println("Your application is denied."); } else { System.out.println("Welcome to Mars University!"); }

5 Relational expressions The used in an if or if/else statement is the same kind of value seen in the middle of a for loop. for (int i = 1; i <= 10; i++) These conditions are called relational expressions. Relational expressions use one of the following six relational operators: OperatorMeaningExampleValue == equals == 2true != does not equal 3.2 != 2.5true < less than 10 < 5false > greater than 10 > 5true <= less than or equal to 126 <= 100false >= greater than or equal to 5.0 >= 5.0true

6 Evaluating rel. expressions The relational operators can be used in a bigger expression with the mathematical operators we learned earlier. Relational operators have a lower precedence than mathematical operators, so they are evaluated last. Example: 5 * 7 >= * (7 - 1) 5 * 7 >= * 6 35 >= >= 33 true Relational operators cannot be "chained" in the way that you have seen in algebra. Example: 2 <= x <= 10 true <= 10 error!

7 Nested if/else statements Nested if/else statement: A chain of if/else that can select between many different outcomes based on several conditions. General syntax (shown with three different outcomes, but any number of else if statements can be added in the middle): if ( ) { ; } else if ( ) { ; } else { ; } Example: int grade = console.nextInt(); if (grade >= 90) { System.out.println("Congratulations! An A!"); } else if (grade >= 80) { System.out.println("Your grade is B. Not bad."); } else if (grade >= 70) { System.out.println("You got a C. Work harder!"); }

8 Structures of if/else code Choose 1 of many paths: (use this when the conditions are mutually exclusive) if ( ) { ; } else if ( ) { ; } else { ; } Choose 0 or 1 of many paths: (use this when the conditions are mutually exclusive and any action is optional) if ( ) { ; } else if ( ) { ; } else if ( ) { ; } Choose 0, 1, or many of many paths: (use this when the conditions/actions are independent of each other) if ( ) { ; } if ( ) { ; } if ( ) { ; }

9 Comparing objects The relational operators such as < and == only behave correctly on primitive values. Objects such as String, Point, and Color can be compared for equality by calling a method named equals. Example (incorrect): String name = console.next(); if (name == "Teacher") { System.out.println("You must be a swell guy!"); } Example (correct): String name = console.next(); if (name.equals("Teacher")) { System.out.println("You must be a swell guy!"); }

10 String condition methods There are several methods of a String object that can be used as conditions in if statements: MethodDescription equals(String) whether two Strings contain exactly the same characters equalsIgnoreCase(String) whether two Strings contain the same characters, ignoring upper vs. lower case differences startsWith(String) whether one String contains the other's characters at its start endsWith(String) whether one String contains the other's characters at its end

11 String condition examples Scanner console = new Scanner(System.in); System.out.print("Type your full name and title: "); String name = console.nextLine(); if (name.endsWith("Ph. D.")) { System.out.println("Hello, doctor!"); } if (name.startsWith("Ms.")) { System.out.println("Greetings, Ma'am."); } if (name.equalsIgnoreCase("marty stepp")) { System.out.println("Welcome, master! Command me!"); } if (name.toLowerCase().indexOf("jr.") >= 0) { System.out.println("Your parent has the same name!"); }

12 Conditions and Scanner A Scanner object has methods that can be used to test whether the upcoming input token is of a given type: Each of these methods waits for the user to type input tokens and press Enter, then reports a true or false answer. MethodDescription hasNext() Whether or not the next token can be read as a String (always true for console input) hasNextInt() Whether or not the next token can be read as an int hasNextDouble() Whether or not the next token can be read as a double hasNextLine() Whether or not the next line of input can be read as a String (always true for console input)

13 Scanner condition example The Scanner 's hasNext___ methods are very useful for testing whether the user typed the right kind of token for our program to use, before we read it (and potentially crash!). Scanner console = new Scanner(System.in); System.out.print("How old are you? "); if (console.hasNextInt()) { int age = console.nextInt(); System.out.println("Retire in " + (65 - age) + " years."); } else { System.out.println("You did not type an integer."); } System.out.print("Type 10 numbers: "); for (int i = 1; i <= 10; i++) { if (console.hasNextInt()) { System.out.println("Integer: " + console.nextInt()); } else if (console.hasNextDouble()) { System.out.println("Real number: " + console.nextDouble()); }

14 Methods that Return Values Java's Math class Writing methods that return values

15 Java's Math class Java has a class called Math that has several useful methods that perform mathematical calculations. The Math methods are called by writing: Math. ( ) Method nameDescription abs(value)absolute value cos(value)cosine, in radians log(value)logarithm base e max(value1, value2)larger of two values min(value1, value2)smaller of two values pow(value1, value2)value1 to the value2 power random()random double between 0 and 1 round(value)round to nearest whole number sin(value)sine, in radians sqrt(value)square root

16 Methods that "return" values The methods of the Math class do not print their results to the console. Instead, a call to one of these methods can be used as an expression or part of an expression. The method evaluates to produce (or return) a numeric result. The result can be printed or used in a larger expression. Example: double squareRoot = Math.sqrt(121.0); System.out.println(squareRoot); // 11.0 int absoluteValue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5

17 Methods that return values Declaring a method that returns a value: public static ( ) { ; } Returning a value from a method: return ; Example: // Returns the given number cubed (to the third power). public static int cube(int number) { return number * number * number; }

18 Behavior of return Just as parameters let you pass information into a method from outside, return values let you pass information out from a method to its caller. The method call can be used as an expression. The method call 'evaluates' to be the number/value that you return. public static void main(String[] args) { Scanner console = new Scanner(System.in); int square = getNumber(console); } public static int getNumber(Scanner console) { System.out.print("Enter a number: "); int number = console.nextInt(); return number * number; }

19 Example returning methods // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { return 5.0 / 9.0 * degreesF - 32; } // Converts Celsius to Fahrenheit. public static double cToF(double degreesC) { return 9.0 / 5.0 * degreesC + 32; } // Converts kilograms to pounds. public static int factorial(int n) { int product = 1; for (int i = 1; i <= n; i++) { product = product * i; } return product; }