Download presentation
Presentation is loading. Please wait.
Published byFrancis Solomon Wilson Modified over 9 years ago
1
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 Suggested self-checks: Section 3.9 #5-7, 11-12, 18; Section 4.10 #5-23 These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty Stepp's expressed written permission. All rights reserved.
2
2 Conditional Execution The if statement The if/else statement
3
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
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
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 1 + 1 == 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
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 >= 3 + 5 * (7 - 1) 5 * 7 >= 3 + 5 * 6 35 >= 3 + 30 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
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
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
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
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
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
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
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
14 Methods that Return Values Java's Math class Writing methods that return values
15
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
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
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
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
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; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.