Building Java Programs Chapter 4 Conditional Execution Copyright
Building Java Programs Chapter 4: Conditional Execution Copyright 2006 by Pearson Education 1
Chapter outline n loop techniques n n n conditional execution n n cumulative sum fencepost loops the if statement and the if/else statement relational expressions nested if/else statements subtleties of conditional execution n n object equality factoring if/else code text processing methods with conditional execution: revisiting return values Copyright 2006 by Pearson Education 2
Cumulative sum reading: 4. 1 Copyright 2006 by Pearson Education 3
Adding many numbers n Consider this code to read and add three values: Scanner console = new Scanner(System. in); System. out. print("Type a number: "); int num 1 = console. next. Int(); System. out. print("Type a number: "); int num 2 = console. next. Int(); System. out. print("Type a number: "); int num 3 = console. next. Int(); int sum = num 1 + num 2 + num 3; System. out. println("The sum is " + sum); Copyright 2006 by Pearson Education 4
A cumulative sum n The variables num 1, num 2, and num 3 are unnecessary: Scanner console = new Scanner(System. in); System. out. print("Type a number: "); int sum = console. next. Int(); System. out. print("Type a number: "); sum += console. next. Int(); System. out. println("The sum is " + sum); n cumulative sum: A variable that keeps a sum-inprogress and is updated many times until the task of summing is finished. n The variable sum in the above code is a cumulative sum. Copyright 2006 by Pearson Education 5
Failed cumulative sum loop n How could we modify the code to sum 100 numbers? n n Creating 100 copies of the same code would be redundant. An incorrect solution: Scanner console = new Scanner(System. in); for (int i = 1; i <= 100; i++) { int sum = 0; System. out. print("Type a number: "); sum += console. next. Int(); } // sum is undefined here System. out. println("The sum is " + sum); n The scope of sum is inside the for loop, so the last line of code fails to compile. Copyright 2006 by Pearson Education 6
Fixed cumulative sum loop n A corrected version of the sum loop code: Scanner console = new Scanner(System. in); int sum = 0; for (int i = 1; i <= 100; i++) { System. out. print("Type a number: "); sum += console. next. Int(); } System. out. println("The sum is " + sum); n The key idea: Cumulative sum variables must always be declared outside the loops that update them, so that they will continue to live after the loop is finished. Copyright 2006 by Pearson Education 7
User-guided cumulative sum n User input can control the number of loop repetitions: Scanner console = new Scanner(System. in); System. out. print("How many numbers to add? "); int count = console. next. Int(); int sum = 0; for (int i = 1; i <= count; i++) { System. out. print("Type a number: "); sum += console. next. Int(); } System. out. println("The sum is " + sum); n An example output: How many numbers to add? 3 Type a number: 2 Type a number: 6 Type a number: 3 The sum is 11 Copyright 2006 by Pearson Education 8
Variation: cumulative product n The same idea can be used with other operators, such as multiplication which produces a cumulative product: Scanner console = new Scanner(System. in); System. out. print("Raise 2 to what power? "); int exponent = console. next. Int(); int product = 1; for (int i = 1; i <= exponent; i++) { product = product * 2; } System. out. println("2 to the " + exponent + " = " + product); n Exercises: n n Change the above code so that it also prompts for the base, instead of always using 2. Change the above code into a method which accepts a base a and exponent b as parameters and returns ab. Copyright 2006 by Pearson Education 9
Cumulative sum question n Write a program that reads input of the number of hours two employees have worked and displays each employee's total and the overall total hours. n n The company doesn't pay overtime, so cap any day at 8 hours. Example log of execution: Employee 1: How many days? 3 Hours? 6 Hours? 12 Hours? 5 Employee 1's total hours = 19 Employee 2: How many days? 2 Hours? 11 Hours? 6 Employee 2's total hours = 14 Total hours for both = 33 Copyright 2006 by Pearson Education 10
Cumulative sum answer // Computes the total paid hours worked by two employees. // The company does not pay for more than 8 hours per day. // Uses a "cumulative sum" loop to compute the total hours. import java. util. *; public class Hours { public static void main(String[] args) { Scanner console = new Scanner(System. in); int hours 1 = process. Employee(console, 1); int hours 2 = process. Employee(console, 2); } int total = hours 1 + hours 2; System. out. println("Total hours for both = " + total); . . . Copyright 2006 by Pearson Education 11
Cumulative sum answer 2. . . // Reads hours information about one employee with the given number. // Returns the total hours worked by the employee. public static int process. Employee(Scanner console, int number) { System. out. print("Employee " + number + ": How many days? "); int days = console. next. Int(); // total. Hours is a cumulative sum of all days' hours worked. int total. Hours = 0; for (int i = 1; i <= days; i++) { System. out. print("Hours? "); Copyright 2006 by Pearson Education 12
Fencepost loops reading: 4. 1 Copyright 2006 by Pearson Education 13
The fencepost problem n Problem: Write a static method named print. Numbers that prints each number from 1 to a given maximum, separated by commas. For example, the method call: print. Numbers(5) should print: 1, 2, 3, 4, 5 Copyright 2006 by Pearson Education 14
Flawed solution 1 n A flawed solution: public static void print. Numbers(int max) { for (int i = 1; i <= max; i++) { System. out. print(i + ", "); } System. out. println(); // to end the line of output } n Output from print. Numbers(5): 1, 2, 3, 4, 5, Copyright 2006 by Pearson Education 15
Flawed solution 2 n Another flawed solution: public static void print. Numbers(int max) { for (int i = 1; i <= max; i++) { System. out. print(", " + i); } System. out. println(); // to end the line of output } n Output from print. Numbers(5): , 1, 2, 3, 4, 5 Copyright 2006 by Pearson Education 16
Fence post analogy n n We print n numbers but need only n - 1 commas. This problem is similar to the task of building a fence with lengths of wire separated by posts. n n n often called a fencepost problem If we repeatedly place a post and wire, the last post will have an extra dangling wire. A flawed algorithm: for (length of fence) { place some post. place some wire. } Copyright 2006 by Pearson Education 17
Fencepost loop n The solution is to add an extra statement outside the loop that places the inital "post. " n n This is sometimes also called a fencepost loop or a "loop-and-a-half" solution. The revised algorithm: place a post. for (length of fence - 1) { place some wire. place some post. } Copyright 2006 by Pearson Education 18
Fencepost method solution n A version of print. Numbers that works: public static void print. Numbers(int max) { System. out. print(1); for (int i = 2; i <= max; i++) { System. out. print(", " + i); } System. out. println(); // to end the line of output } OUTPUT from print. Numbers(5): 1, 2, 3, 4, 5 Copyright 2006 by Pearson Education 19
Fencepost question n Write a method named print. Factors that, when given a number, prints its factors in the following format (using an example of 24 for the parameter value): [1, 2, 3, 4, 6, 8, 12, 24] Copyright 2006 by Pearson Education 20
Fencepost question n Write a Java program that reads a base and a maximum power and prints all of the powers of the given base up to that max, separated by commas. Base: 2 Max exponent: 9 The first 9 powers of 2 are: 2, 4, 8, 16, 32, 64, 128, 256, 512 Copyright 2006 by Pearson Education 21
if/else statements reading: 4. 2 Copyright 2006 by Pearson Education 22
The if statement n if statement: A Java statement that executes a block of statements only if a certain condition is true. n n n If the condition is not true, the block of statements is skipped. General syntax: if (<condition>) { <statement> ; . . . <statement> ; } Example: double gpa = console. next. Double(); if (gpa >= 2. 0) { System. out. println("Your application is accepted. "); } Copyright 2006 by Pearson Education 23
if statement flow diagram Copyright 2006 by Pearson Education 24
The if/else statement n 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 it is false. n n General syntax: if (<condition>) { <statement(s)> ; } else { <statement(s)> ; } Example: double gpa = console. next. Double(); if (gpa >= 2. 0) { System. out. println("Welcome to Mars University!"); } else { System. out. println("Your application is denied. "); } Copyright 2006 by Pearson Education 25
if/else flow diagram Copyright 2006 by Pearson Education 26
Relational expressions n The <condition> used in an if or if/else statement is the same kind seen in a for loop. for (int i = 1; i <= 10; i++) { n n 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 true < less than 10 < 5 false > greater than 10 > 5 true <= less than or equal to 126 <= 100 false >= greater than or equal to 5. 0 >= 5. 0 Copyright 2006 by Pearson Education true 27
Evaluating rel. expressions n Relational operators have lower precedence than math operators. n Example: 5 * 7 35 35 true n >= >= 3 + 5 * (7 - 1) 3 + 5 * 6 3 + 30 33 Relational operators cannot be "chained" as they can in algebra. n Example: 2 <= x <= 10 true <= 10 error! Copyright 2006 by Pearson Education 28
if/else question n Write code to read a number from the user and print whether it is even or odd using an if/else statement. n Example executions: Type a number: 42 Your number is even Type a number: 17 Your number is odd Copyright 2006 by Pearson Education 29
Loops with if/else n Loops can be used with if/else statements: int nonnegatives = 0, negatives = 0; for (int i = 1; i <= 10; i++) { int next = console. next. Int(); if (next >= 0) { nonnegatives++; } else { negatives++; } } n public static void print. Even. Odd(int max) { for (int i = 1; i <= max; i++) { if (i % 2 == 0) { System. out. println(i + " is even"); } else { System. out. println(i + " is odd"); } } } Copyright 2006 by Pearson Education 30
Nested if/else statements n nested if/else statement: A chain of if/else that chooses between outcomes using many conditions. n n General syntax: if (<condition>) { <statement(s)> ; } else { <statement(s)> ; } Example: if (number > 0) { System. out. println("Positive"); } else if (number < 0) { System. out. println("Negative"); } else { System. out. println("Zero"); } Copyright 2006 by Pearson Education 31
Nested if/else variations n A nested if/else can end with an if or an else. n n n If it ends with else, one of the code paths must be taken. If it ends with if, the program might not execute any path. Example ending with if: 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. "); } n n Are there any cases where this code will not print a message? How could we modify it to print a message to non-medalists? Copyright 2006 by Pearson Education 32
Nested if/else flow diagram if (<condition>) { <statement(s)> ; } else { <statement(s)> ; } Copyright 2006 by Pearson Education 33
Nested if/else/if diagram if (<condition>) { <statement(s)> ; } else if (<condition>) { <statement(s)> ; } Copyright 2006 by Pearson Education 34
Sequential if diagram if (<condition>) { <statement(s)> ; } Copyright 2006 by Pearson Education 35
Structures of if/else code n Choose 1 of many paths: n (conditions are mutually exclusive) if (<condition>) { <statement(s)>; } else { <statement(s)>; } n Choose 0 or 1 of many paths: (conditions are mutually exclusive and any action is optional) if (<condition>) { <statement(s)>; } else if (<condition>) { <statement(s)>; } Choose 0, 1, or many of many paths: (conditions/actions are independent of each other) if (<condition>) { <statement(s)>; }Copyright 2006 by Pearson Education 36
Which nested if/else to use? n Which if/else construct is most appropriate? n n n 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 upperclass 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. Copyright 2006 by Pearson Education 37
Which nested if/else answers n Which if/else construct is most appropriate? n 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). n n Printing whether a number is even or odd. n n nested if / else Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5. n n simple if / else Printing whether a user is lower-class, middle-class, or upperclass based on their income. n n nested if / else if sequential if / if Printing a user's grade of A, B, C, D, or F based on their percentage in the course. n nested if / else Copyright 2006 by Pearson Education 38
How to comment: if/else n Comments shouldn't describe the condition being tested. n n Instead, describe why you are performing that test, 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 (gpa 1 > gpa 2) { // print that student 1 had the greater GPA System. out. println("The first student had the greater GPA. "); } else if (gpa 2 > gpa 1) { // 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!"); } n Better example: // Print a message about which student had the higher grade point average. if (gpa 1 > gpa 2) { System. out. println("The first student had the greater GPA. "); } else if (gpa 2 > gpa 1) { System. out. println("The second student's GPA was higher. "); } else { // gpa 1 == gpa 2 (a tie) System. out. println("There has been a tie!"); } Copyright 2006 by Pearson Education 39
How to comment: if/else 2 n Sometimes putting comments on the if/else bodies themselves is more helpful. n Example: if (guess. Again == 1) { // user wants to guess again; reset game state // and start another game System. out. println("Playing another game. "); score = 0; reset. Game(); play(); } else { // user is finished playing; print their best score System. out. println("Thank you for playing. "); System. out. println("Your score was " + score); } Copyright 2006 by Pearson Education 40
Math. max/min vs. if/else n 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. n n 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 = if (b < d) d = b; } if (c < d) d = c; } double d = a; { // d should be smallest of a, b, c { Math. min(a, Math. min(b, c)); Copyright 2006 by Pearson Education 41
Subtleties of conditional execution reading: 4. 3 Copyright 2006 by Pearson Education 42
Comparing objects n Relational operators such as < and == only behave correctly on primitive values. n n The == operator on Strings often evaluates to false even when the Strings have the same letters in them. Example (incorrect): Scanner console = new Scanner(System. in); System. out. print("What is your name? "); String name = console. next(); if (name == "Barney") { System. out. println("I love you, you love me, "); System. out. println("We're a happy family!"); } n This example code will compile, but it will never print the message, even if the user does type Barney Copyright 2006 by Pearson Education 43
The equals method n Objects (such as String, Point, and Color) should be compared for equality by calling a method named equals. n Example (correct): Scanner console = new Scanner(System. in); System. out. print("What is your name? "); String name = console. next(); if (name. equals("Barney")) { System. out. println("I love you, you love me, "); System. out. println("We're a happy family!"); } Copyright 2006 by Pearson Education 44
Another example n n The == operator on objects actually compares whether two variables refer to the same object. The equals method compares whether two objects have the same state as each other. n n Given the following code: Point p 1 = new Point(3, 8); Point p 2 = new Point(2, -4); Point p 3 = p 2; p 1 x 3 y 8 What is printed? p 2 x 2 y -4 if (p 1 == p 2) { System. out. println("1"); } if (p 1. equals(p 2)) { System. out. println("2"); } if (p 2 == p 3) { System. out. println("3"); } Copyright 2006 by Pearson Education p 3 45
String condition methods n There are several methods of a String object that can be used as conditions in if statements: Method Description equals(str) whether two strings contain exactly the same characters equals. Ignore. Case(str) whether two strings contain the same characters, ignoring upper vs. lower case differences starts. With(str) whether one string contains the other's characters at its start ends. With(str) whether one string contains the other's characters at its end Copyright 2006 by Pearson Education 46
String condition examples n Hypothetical examples, assuming the existence of various String variables: n n if (title. ends. With("Ph. D. ")) { System. out. println("How's life in the ivory tower? "); } if (full. Name. starts. With("Queen")) { System. out. println("Greetings, your majesty. "); } if (last. Name. equals. Ignore. Case("lumberg")) { System. out. println("I need your TPS reports!"); } if (name. to. Lower. Case(). index. Of("jr. ") >= 0) { System. out. println("You share your parent's name. "); } Copyright 2006 by Pearson Education 47
Factoring if/else code n factoring: extracting common/redundant code n n 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; } Copyright 2006 by Pearson Education int x = 2 * a + 1; 48
Code in need of factoring n The following example has a lot of redundant code: 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. next. Int(); } else if (money < 1000) { System. out. println("You have, $" + money + " left. "); System. out. print("Consider betting moderately. "); System. out. print("How much do you want to bet? "); bet = console. next. Int(); } else { System. out. println("You have, $" + money + " left. "); System. out. print("You may bet liberally. "); System. out. print("How much do you want to bet? "); bet = console. next. Int(); } Copyright 2006 by Pearson Education 49
Code after factoring n Factoring tips: n n If the start of each branch is the same, move it before the if/else. If the end of each branch is the same, move it 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. next. Int(); Copyright 2006 by Pearson Education 50
Text processing with String and char reading: 4. 4 Copyright 2006 by Pearson Education 51
Type char n char: A primitive type representing single characters. n Individual characters inside a String are stored as char values. Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4' or 'n' or ''' n It is legal to have variables, parameters, returns of type char n char letter = 'S'; System. out. println(letter); Copyright 2006 by Pearson Education // S 52
The char. At method n The characters of a string can be accessed as char values using the String object's char. At method. String word = console. next(); char first. Letter = word. char. At(0); if (first. Letter == 'c') { System. out. println("That's good enough for me!"); } n We often use for loops that print or examine each character. String name = "tall"; for (int i = 0; i < name. length(); i++) { System. out. println(title. char. At(i)); } Output: t a l l Copyright 2006 by Pearson Education 53
Text processing n text processing: Examining, editing, formatting text. n n Text processing often involves for loops that examine the characters of a string one by one. You can use char. At to search for or count occurrences of a particular value in a string. // Returns the count of occurrences of c in s. public static int count(String s, char c) { int count = 0; for (int i = 0; i < s. length(); i++) { if (s. char. At(i) == 't') { count++; } } return count; } n count("mississippi", 'i') returns 4 Copyright 2006 by Pearson Education 54
Other things to do with char n char values can be concatenated with strings. char initial = 'P'; System. out. println(initial + " Diddy"); n You can compare char values with relational operators: n n n 'a' < 'b' and 'Q' != 'q' Note that you cannot use these operators on a String. An example that prints the alphabet: for (char c = 'a'; c <= 'z'; c++) { System. out. print(c); } Copyright 2006 by Pearson Education 55
char/int and type casting n All char values are assigned numbers internally by the computer, called ASCII values. n n n Examples: 'A' is 65, 'B' is 66, 'a' is 97, 'b' is 98 Mixing char and int causes automatic conversion to int. 'a' + 10 is 107, 'A' + 'A' is 130 To convert an integer into the equivalent character, type cast it. (char) ('a' + 2) is 'c' Copyright 2006 by Pearson Education 56
char vs. String n 'h' is a char n n n char c = 'h'; char values are primitive; you cannot call methods on them can't say c. length() or c. to. Upper. Case() "h" is a String s = "h"; n n n Strings are objects; they contain methods that can be called can say s. length() 1 can say s. to. Upper. Case() "H" can say s. char. At(0) 'h' What is s + 1 ? What is c + 1 ? What is s + s ? What is c + c ? Copyright 2006 by Pearson Education 57
Text processing questions n Write a method named pig. Latin. Word that accepts a String as a parameter and outputs that word in simplified Pig Latin, by placing the word's first letter at the end followed by the suffix ay. n n n pig. Latin. Word("hello") pig. Latin. Word("goodbye") prints ello-hay prints oodbye-gay Write methods named encode and decode that accept a String as a parameter and outputs that String with each of its letters increased or decreased by 1. n n encode("hello") decode("ifmmp") Copyright 2006 by Pearson Education prints ifmmp prints hello 58
Text processing question n Write a method print. Name that accepts a full name as a parameter, and prints the last name followed by a comma, followed by the first name and middle initial. n For example, print. Name("James Tiberius Kirk"); Kirk, James T. Method name char. At(index) would output: Description character at a specific index. Of(str) index where the start of the given string appears in this string (-1 if it is not there) length() number of characters in this string substring(index 1, index 2) the characters in this string from index 1 (inclusive) to index 2 (exclusive) to. Lower. Case() a new string with all lowercase letters to. Upper. Case() a new string with all uppercase letters Copyright 2006 by Pearson Education 59
Methods with if/else reading: 4. 5 Copyright 2006 by Pearson Education 60
if/else with return n Methods can be written to return different values under different conditions using if/else statements: public static int min(int a, int b) { if (a > b) { return a; } else { return b; } } n Another example that returns the first word in a string: public static String first. Word(String s) { int index = s. index. Of(" "); if (index >= 0) { return s. substring(0, index); } else { // only one word in String return s; } } Copyright 2006 by Pearson Education 61
All code paths must return n It is an error not to return a value in every path: public static int min(int a, int b) { if (a > b) { return b; } // Error; not all paths return a value. What if a <= b ? } n Two fixed versions of the code: public static int min(int a, int b) { if (a > b) { return b; } else { return a; } } public static int min(int a, int b) { if (a > b) { return b; } return a; } Copyright 2006 by Pearson Education 62
All code paths must return 2 n The following code also does not compile: public static int min(int a, int b) { if (a >= b) { return b; } else if (a < b) { return a; } } n It produces the "Not all paths return a value" error. n n To our eyes, it seems that all paths do return a value. But the compiler thinks that if/else/if code might choose not to execute any branch, so it refuses to accept this code. Copyright 2006 by Pearson Education 63
for loops with if/else return n Methods with loops that return values must consider the case where the loop does not execute the return. public static int index. Of(String s, char c) { for (int i = 0; i < s. length(); i++) { if (s. char. At(i) == c) { return i; } } // error; what if c does not occur in s? } n A better version that returns -1 when c is not found: public static int index. Of(String s, char c) { for (int i = 0; i < s. length(); i++) { if (s. char. At(i) == c) { return i; } } return -1; // not found } Copyright 2006 by Pearson Education 64
if/else return question n Write a method named num. Unique that accepts two integer parameters and returns how many unique values were passed. n n Write a method named count. Factors that returns the number of factors of an integer. n n For example, num. Unique(3, 7) returns 2 because 3 and 7 are two unique numbers, but num. Unique(4, 4) returns 1 because 4 and 4 only represent one unique number. For example, count. Factors(60) returns 11 because 1, 2, 3, 4, 5, 6, 10, 15, 20, 30, and 60 are factors of 60. Modify the pig. Latin. Word and encode/decode methods seen previously so that they return their results rather than printing them. Copyright 2006 by Pearson Education 65
Method return question n Write a program that prompts the user for a maximum integer and prints out a list of all prime numbers up to that maximum. Here is an example log of execution: Maximum number? 50 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 14 total primes Copyright 2006 by Pearson Education 66
Method return answer 1 // Prompts for a maximum number and prints each prime up to that maximum. import java. util. *; public class Primes { public static void main(String[] args) { // read max from user Scanner console = new Scanner(System. in); System. out. print("Maximum number? "); int max = console. next. Int(); print. All. Primes(max); } public static void print. All. Primes(int max) { System. out. print(2); // print first prime (fencepost) // A loop to print the rest of the prime numbers. int primes = 1; for (int i = 3; i <= max; i++) { if (count. Factors(i) == 2) { // i is prime System. out. print(", " + i); primes++; } } System. out. println(); System. out. println(primes + " total primes"); } Copyright 2006 by Pearson Education 67
Method return answer 2. . . } // Returns how many factors the given number has. public static int count. Factors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { count++; // i is a factor of number } } return count; } Copyright 2006 by Pearson Education 68
- Slides: 68