Presentation is loading. Please wait.

Presentation is loading. Please wait.

Building Java Programs

Similar presentations


Presentation on theme: "Building Java Programs"— Presentation transcript:

1 Building Java Programs
Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or modified without expressed permission from the authors. All rights reserved.

2 Chapter outline conditional execution
the if statement the if/else statement relational expressions nested if/else statements subtleties of conditional execution factoring if/else code comparing objects with the .equals method methods with conditional execution revisiting return values

3 if/else statements suggested reading: 4.2

4 The if statement 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 (<condition>) { <statement(s)> ; } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Your application is accepted.");

5 if statement flow diagram

6 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 (<condition>) { <statement(s)> ; } else { } Example: double gpa = console.nextDouble(); if (gpa <= 2.0) { System.out.println("Your application is denied."); System.out.println("Welcome to Mars University!");

7 if/else flow diagram

8 Relational expressions
The <condition> 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++) { The conditions are actually of type boolean, seen in Ch. 5. These conditions are called relational expressions and use one of the following six relational operators: Operator Meaning Example Value == equals 1 + 1 == 2 true != does not equal 3.2 != 2.5 < less than 10 < 5 false > greater than 10 > 5 <= less than or equal to 126 <= 100 >= greater than or equal to 5.0 >= 5.0 Note that == tests equality, not = . The = is used for the assignment operator!

9 Evaluating rel. expressions
Relational operators have a lower precedence than mathematical operators. Example: 5 * 7 >= * (7 - 1) 5 * 7 >= * 6 35 >= 35 >= 33 true Relational operators cannot be "chained" as they can in algebra. 2 <= x <= 10 true <= 10 error!

10 if/else question Write code to read a number from the user and print whether that number is even or odd using an if/else statement. Example executions: Type a number: 42 Your number is even Type a number: 17 Your number is odd

11 Loops with if/else Loops can be used with if/else statements:
int nonnegatives = 0, negatives = 0; for (int i = 1; i <= 10; i++) { int next = console.nextInt(); if (next >= 0) { nonnegatives++; } else { negatives++; } A loop that prints the factors of a number: public static void printFactors(int n) { for (int i = 1; i <= n; i++) { if (n % i == 0) { System.out.println(i + " is a factor");

12 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 here with three different outcomes): if (<condition>) { <statement(s)> ; } else if (<condition>) { } else { } A nested if/else statement can end with an if or an else. Example: if (place == 1) { System.out.println("You win the gold medal!"); } else if (place == 2) { System.out.println("You win a silver medal!"); } else if (place == 3) { System.out.println("You earned a bronze medal."); How could we modify it to print a message to non-medalists?

13 Nested if/else flow diagram
if (<condition>) { <statement(s)> ; } else if (<condition>) { } else { }

14 Nested if/else/if flow diagram
if (<condition>) { <statement(s)> ; } else if (<condition>) { }

15 Sequential if flow diagram
if (<condition>) { <statement(s)> ; }

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

17 Which nested if/else to use?
Which if/else construct is most appropriate to perform each of the following tasks? Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8). Printing whether a number is even or odd. Printing whether a user is lower-class, middle-class, or upper-class based on their income. Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5. Printing a user's grade of A, B, C, D, or F based on their percentage in the course.

18 How to comment: if/else
Comments on an if statement don't need to describe exactly what the if statement is testing. Instead, they should describe why you are performing that test, and/or what you intend to do based on its result. Bad example: // Test whether student 1's GPA is better than student 2's if (gpa1 > gpa2) { // print that student 1 had the greater GPA System.out.println("The first student had the greater GPA."); } else if (gpa2 > gpa1) { // print that student 2 had the greater GPA System.out.println("The second student's GPA was higher."); } else { // there was a tie System.out.println("There has been a tie!"); } Better example: // Print a message about which student had the higher grade point average. } else { // gpa1 == gpa2 (a tie)

19 How to comment: if/else 2
If an if statement's test is straightforward, and if the actions to be taken in the bodies of the if/else statement are very different, sometimes putting comments on the bodies themselves is more helpful. Example: if (guessAgain == 1) { // user wants to guess again; reset game state and // play another game System.out.println("Playing another game."); score = 0; resetGame(); play(); } else { // user is finished playing; print their best score System.out.println("Thank you for playing."); System.out.println("Your score was " + score); }

20 Math.max/min vs. if/else
Many if/else statements that choose the larger or smaller of 2 numbers can be replaced by a call to Math.max or Math.min. int z; // z should be larger of x, y if (x > y) { z = x; } else { z = y; } int z = Math.max(x, y); double d = a; // d should be smallest of a, b, c if (b < d) { d = b; } if (c < d) { d = c; } double d = Math.min(a, Math.min(b, c));

21 Subtleties of conditional execution
suggested reading: 4.3

22 Factoring if/else code
factoring: extracting a common part of code to reduce redundancy Factoring if/else code reduces the size of the if and else statements and can sometimes eliminate the need for if/else altogether. Example: int x; if (a == 1) { x = 3; } else if (a == 2) { x = 5; } else { // a == 3 x = 7; } int x = 2 * a + 1;

23 Code in need of factoring
The following example has a lot of redundant code in the if/else: if (money < 500) { System.out.println("You have, $" + money + " left."); System.out.print("Caution! Bet carefully."); System.out.print("How much do you want to bet? "); bet = console.nextInt(); } else if (money < 1000) { System.out.print("Consider betting moderately."); } else { System.out.print("You may bet liberally."); }

24 Code after factoring If the beginning of each if/else branch is essentially the same, try to move it out before the if/else. If the end of each if/else branch is the same, try to move it out after the if/else. System.out.println("You have, $" + money + " left."); if (money < 500) { System.out.print("Caution! Bet carefully."); } else if (money < 1000) { System.out.print("Consider betting moderately."); } else { System.out.print("You may bet liberally."); } System.out.print("How much do you want to bet? "); bet = console.nextInt();

25 Comparing objects: .equals
The relational operators such as < and == only behave correctly on primitive values. Objects such as String, Point, and Color should 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 person!"); } This example code will compile, but it will never print the message. The == operator on Strings usually returns false even when the Strings have the same letters in them. Example (correct): if (name.equals("Teacher")) {

26 String condition methods
There are several methods of a String object that can be used as conditions in if statements: Method Description 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

27 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("boss")) { System.out.println("Welcome, master! Command me!"); if (name.toLowerCase().indexOf("jr.") >= 0) { System.out.println("Your parent has the same name!");


Download ppt "Building Java Programs"

Similar presentations


Ads by Google