Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Chapter Goals  To implement decisions using if statements  To implement while, for, and do loops  To understand nested loops  To develop strategies for testing your programs  To validate user input

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Decisions

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Performing Comparisons  Most programs need the ability to test conditions and make decisions based on the outcomes of those tests.  The primary tool for testing conditions is the if statement  If statement which tests whether a boolean expression has the value true or false.  Most of the conditions in a program involve comparisons, which are performed using the relational operators and the equality operators.

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Relational Operators  These operators test the relationship between two numbers, returning a boolean result. < Less than > Greater than <= Less than or equal to >= Greater than or equal to  Examples: 5 < 3  false 5 > 3  true 3 > 3  false 5 <= 3  false 5 >= 3  true 3 >= 3  true

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Relational Operators  operands can be of different types. If an int value is compared with a double value, the int value will be converted to double before the comparison is performed.  The arithmetic operators take precedence over the relational operators, so Java would interpret a - b * c < d + e as (a – (b * c)) < (d + e) Check for precedence with other operators: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Equality Operators  Testing whether two values are equal or not equal is done using the equality operators: == Equal to != Not equal to  The equality operators have lower precedence than the relational operators.  Examples of the equality operators: 6 == 2  false 6 != 2  true 2 == 2  true 2 != 2  false

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 Equality Operators  As with the relational operators, the types of the operands can be different.  If an int operand is compared to a double operand, the int value is converted automatically to double type before the comparison is performed: 2 == 2.0  true 2 == 2.1  false

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Testing Floating-Point Numbers for Equality  Because of round-off error, floating-point numbers that seem as though they should be equal may not be.  For example, the condition 1.2 - 1.1 == 0.1 is false, because the value of 1.2 - 1.1 is 0.09999999999999987, not 0.1. Try this in interaction pane!  One way to avoid problems with round-off error is to test whether floating-point numbers are close enough, rather than testing whether they’re equal.

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Logical Operators  You often need to combine the results of comparisons when making complex decisions  The && operator is called and Yields true only when both conditions are true.  The || operator is called or Yields the result true if at least one of the conditions is true.  The ! Operator is called not Yields negation  ! is a unary operator. && and || are binary operators.  All logical operators expect boolean operands and produce boolean results

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Logical Operators

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13 Logical Operators  To test if water is liquid at a given temperature: if (temp > 0 && temp < 100) { System.out.println("Liquid"); } boolean found = false; if(!found) { //do something }

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Precedence and Associativity of operators

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Precedence and Associativity of And, Or, and Not  The ! operator is right associative.  The && and || operators are left associative.  Java would interpret a = d && e == f as ((a = d)) && (e == f)

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 The if Statement  The if statement allows a program to test a condition  When the if statement is executed: the BooleanExpression is evaluated. If it’s true, then statement is executed. If it’s false, statement is NOT executed. if(BooleanExpression) statement; if(BooleanExpression) { statement1; statement2;... } OR Block: Set of statements within curly braces int actualFloor = floor; if (floor > 13) { actualFloor--; } E.g.

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 The if-else Statement  Flowchart with two branches:  When the if statement is executed: the BooleanExpression is evaluated. If it’s true, then statement/block1 inside if is executed. If it’s false, statement/block2 inside else is executed instead. if(BooleanExpression) statement or block 1 else statement or block 2 int actualFloor = floor; if (floor > 13){ actualFloor--; } else{ actualFloor = floor; } E.g.

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 The if-else if Statement  Test a series of conditions (multiple alternatives)  If BooleanExpression1 is true, then statement or block 1 is executed.  If BooleanExpression1 is false, then BooleanExpression2 is tested. If BooleanExpression2 is true, then statement or block 2 is executed. If BooleanExpression2 is false, then statement or block 3 is executed.  You can have as many else if clauses as is needed.  else clause is optional if (BooleanExpression1) statement or block 1 else if(BooleanExpression2) statement or block 2 else statement or block 3

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 The if-else if Statement  As soon as one of the tests succeeds: The effect is displayed No further tests are attempted.  If none of the tests succeed: The final else clause applies

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 The if-else if Statement  E.g. if (richter >= 8.0) { description = "Most structures fall”; } else if (richter >= 7.0) { description = "Many buildings destroyed”; } else if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } elseif (richter >= 4.5) { description = "Damage to poorly constructed buildings”; } Note that else clause is optional.

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 The if-else if Statement  In this example, must use if/else if/else sequence, not just multiple independent if statements  Error: if (richter >= 8.0) // Didn't use else { description = "Most structures fall”; } if (richter >= 7.0) { description = "Many buildings destroyed”; } if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } if (richter >= 4.5) { "Damage to poorly constructed buildings”; }  The alternatives are no longer exclusive.

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Syntax 5.1 The if Statement

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Programming Question  Write a tester class IfTester to test the use of if condition. In the main method define two variables score and grade. score represents a score of a student for a given test. grade is a character representing the grade of the student based on his/her score. Write a set of statements to prompt the user for a score, find and print the grade of the student. Use following criteria for grading: testScoregrade 100-90A 80-89B 70-79C <70D Sample output:

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Answer import java.util.Scanner; public class IfTester { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter score: "); int score = sc.nextInt(); char grade; if(score>=90 && score<=100) { grade = 'A'; } else if(score>=80) { grade='B'; } else if(score>=70) { grade='C'; } else { grade='D'; } System.out.println("Score ="+score+" Grade="+grade); } IfTester.java

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Testing Objects for Equality  If x and y are two object variables of the same type, the expression x == y tests whether x and y refer to the same object (or both x and y have the value null ).  The references in x and y are being compared, NOT the objects that x and y refer to.

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Both null : statement return true Even if two different object have same content, statement return false if two reference variables reference same object,statement return true

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 The equals Method  The equals method is used to test whether two objects contain matching data.  The value of x.equals(y) is true if the objects that x and y represent are “equal.”  Every Java class supports the equals method, although the definition of “equals” varies from class to class.  For some classes, the value of x.equals(y) is the same as x == y.

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Comparing Strings  When comparing strings, same rule that apply to other objects apply to strings  To test whether two strings are equal to each other, use equals method: if (string1.equals(string2))...  Don't use == for strings! if (string1 == string2) // Not useful  == operator: tests if two strings are stored in the same memory location  equals method: tests equal contents

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Programming Question  Write a class ObjectComparisonTester.java Include following code in your main method to initialize Rectangle objects( java.awt.Rectangle ):  Also include statements to test and print if each possible pair of Rectangle reference variables: 1.refer to the same Rectangle object in memory and 2.Refer to Rectangle objects that contain the same content  Sample run is shown: Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); Copy and modify template from: /net/people/classes/CS160/handouts/cs160_source_code/lec3/templates/ObjectComparisonTester.java

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Answer ObjectComparisonTester.java import java.awt.Rectangle; public class ObjectComparisonTester { public static void main(String args[]) { Rectangle box1 = new Rectangle(5,10,20,30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(); //test and print if box1 and box2 reference same object System.out.println("box1==box2:"+(box1==box2)); //test and print if box1 and box3 reference same object System.out.println("box1==box3:"+(box1==box3)); //test and print if box2 and box3 reference same object System.out.println("box2==box3:"+(box2==box3)); //test and print if box1 and box2 contain same data System.out.println("box1.equlas(box2):"+(box1.equals(box2))); //test and print if box1 and box3 contain same data System.out.println("box1.equlas(box3):"+(box1.equals(box3))); //test and print if box2 and box3 contain same data System.out.println("box2.equlas(box3):"+(box2.equals(box3))); }

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 Object Comparison Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30);

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 Testing for null  null reference refers to no object: String middleInitial = null; // Not set  Can be used in tests: if (middleInitial == null) { System.out.println(firstName + " " + lastName); } else { System.out.println(firstName + " " + middleInitial + ". " + lastName); }  Use ==, (not the equals method), to test for null  null is not the same as the empty string ""

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Relational Operator Examples

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Loops

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Loops A part of a program is repeated over and over, until a specific goal is reached A statements in a loop are executed while a condition is true. For calculations that require repeated steps

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Types of Loops  Java has three loop statements: while do for  All three use a boolean expression to determine whether or not to continue looping.  All three require a single statement as the loop body. This statement can be a block, however.

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Types of Loops  Which type of loop to use is mostly a matter of convenience. The while statement tests its condition before executing the loop body. The do statement tests its condition after executing the loop body. The for statement test condition before executing the loop body. The for statement is most convenient if the loop is controlled by a variable whose value needs to be updated each time the loop body is executed.

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 The while Loop  How can you “Repeat steps while the balance is less than $20,000?”  With a while loop statement  Syntax while (condition) { statements }  As long condition is true, the statements in the while loop execute. while (condition) { statements } 1 1 2 2

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 The while Loop  Investment problem: You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original investment?  The code: double balance = 10000; double targetBalance = balance *2; int year = 0; while (balance < targetBalance) { year++; double interest = balance * 5/ 100; balance = balance + interest; }

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 Syntax 6.1 while Statement

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 The while Loop  For a variable declared inside a loop body: Variable is created for each iteration of the loop And removed after the end of each iteration double balance = 10000; double targetBalance = balance *2; int year = 0; while (balance < targetBalance) { year++; double interest = balance * RATE / 100; balance = balance + interest; } // interest no longer declared here

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Execution of a while Loop  Step by step execution of the investment while loop:

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Programming Question  Write a class Investment (Investment.java) with following: Instance Variables: balance, rate, year Constructor: two-argument, initialize balance and rate (and years to 0) Instance Method: waitForBalance Keeps accumulating interest until a target balance has been reached. Accepts the target balance as parameter Instance Method: getBalance Returns the current balance Instance Method: getYears Returns the number of years this investment has accumulated interest. Copy and modify the template from handouts folder: /net/people/classes/CS160/handouts/lec03/templates

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Answer 1 /** 2 A class to monitor the growth of an investment that 3 accumulates interest at a fixed annual rate. 4 */ 5 public class Investment 6 { 7 private double balance; 8 private double rate; 9 private int year; 10 11 /** 12 Constructs an Investment object from a starting balance and 13 interest rate. 14 @param aBalance the starting balance 15 @param aRate the interest rate in percent 16 */ 17 public Investment(double aBalance, double aRate) 18 { 19 balance = aBalance; 20 rate = aRate; 21 year = 0; 22 } 23 Continued Investment.java

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 24 /** 25 Keeps accumulating interest until a target balance has 26 been reached. 27 @param targetBalance the desired balance 28 */ 29 public void waitForBalance(double targetBalance) 30 { 31 while (balance < targetBalance) 32 { 33 year++; 34 double interest = balance * rate / 100; 35 balance = balance + interest; 36 } 37 } 38 39 /** 40 Gets the current investment balance. 41 @return the current balance 42 */ 43 public double getBalance() 44 { 45 return balance; 46 } 47

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 48 /** 49 Gets the number of years this investment has accumulated 50 interest. 51 @return the number of years since the start of the investment 52 */ 53 public int getYears() 54 { 55 return year; 56 } 57 }

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Programming Question  Implement a tester class InvestmentTester to test functionality of Investment.java. Include code to print the number of years it takes to double an initial balance of $10000 with 5% interest rate  A sample run is below: Program Run: The investment doubled after 15 years Copy and modify the template from handouts folder: /net/people/classes/CS160/handouts/lec03/templates

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49 Answer 1 /** 2 This program computes how long it takes for an investment 3 to double. 4 */ 5 public class InvestmentTester 6 { 7 public static void main(String[] args) 8 { 9 final double INITIAL_BALANCE = 10000; 10 final double RATE = 5; 11 Investment invest = new Investment(INITIAL_BALANCE, RATE); 12 invest.waitForBalance(2 * INITIAL_BALANCE); 13 int years = invest.getYears(); 14 System.out.println("The investment doubled after " 15 + years + " years"); 16 } 17 } InvestmentTester.java

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50 while Loop Examples

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Common Error: Infinite Loops  Example: forgetting to update the variable that controls the loop int years = 1; while (years <= 20) { double interest = balance * RATE / 100; balance = balance + interest; }  Example: incrementing instead of decrementing int years = 20; while (years > 0) { double interest = balance * RATE / 100; balance = balance + interest; years++; }  These loops run forever – must kill program

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 Problem Solving: Hand-Tracing  A simulation of code execution in which you step through instructions and track the values of the variables.  What value is displayed? 1int n = 1729; 2int sum = 0; 3while (n > 0) 4{4{ 5 int digit = n % 10; 6 sum = sum + digit; 7 n = n / 10; 8}8} 9System.out.println(sum);

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Problem Solving: Hand-Tracing - Step by Step  Step 1  Step 2

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54 Problem Solving: Hand-Tracing - Step by Step  Step 3

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55 Problem Solving: Hand-Tracing - Step by Step  Step 4

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Problem Solving: Hand-Tracing - Step by Step  Step 5

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Problem Solving: Hand-Tracing - Step by Step  Step 6

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Problem Solving: Hand-Tracing - Step by Step  Step 7

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Problem Solving: Hand-Tracing - Step by Step  Step 8

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Problem Solving: Hand-Tracing - Step by Step  Step 9  Step 10 The sum, which is 19, is printed

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 for loop  A compact way to iterate over a range of values  Syntax: for (initialization; termination; increment) { statement(s) }  E.g. print the numbers 1 through 10 class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); }

62 Copyright © 2014 by John Wiley & Sons. All rights reserved.62 The for Loop Sample for loop: for (int counter = 1; counter <= 10; counter++) { System.out.println(counter); } while loop equivalent int counter = 1; // Initialize the counter while (counter <= 10) // Check the counter { System.out.println(counter); counter++; // Update the counter }

63 Copyright © 2014 by John Wiley & Sons. All rights reserved.63 Syntax 6.2 for Statement

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 The for Loop  The initialization is executed once, before the loop is entered.  The condition is checked before each iteration.  The update is executed after each iteration.

65 Copyright © 2014 by John Wiley & Sons. All rights reserved.65 The for Loop  A for loop can count down instead of up: for (int counter = 10; counter >= 0; counter--) { //do something }  The increment or decrement need not be in steps of 1 : for (int counter = 0; counter <= 10; counter += 2) { //do something }

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66 The for Loop  If the counter variable is defined INSIDE the loop header, It does not exist after the loop for (int counter = 1; counter <= 10; counter++) {... } // counter no longer declared here  If you declare the counter variable BEFORE the loop, You can continue to use it after the loop int counter; for (counter = 1; counter <= 10; counter++) {... } // counter still declared here

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67 Programming Question  Modify Investment class to include a method waitForYears. The method should accept the number of years as a parameter and keeps accumulating interest for a given number of years.  Hint: use a for loop to accumulate interest public void waitYears(int numberOfYears)

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68 Answer 1 /** 2 A class to monitor the growth of an investment that 3 accumulates interest at a fixed annual rate 4 */ 5 public class Investment 6 { 7 private double balance; 8 private double rate; 9 private int year; 10 11 /** 12 Constructs an Investment object from a starting balance and 13 interest rate. 14 @param aBalance the starting balance 15 @param aRate the interest rate in percent 16 */ 17 public Investment(double balance, double rate) 18 { 19 this.balance = balance; 20 this.rate = rate; 21 this.year = 0; 22 } 23 Continued Investment.java

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 24 /** 25 Keeps accumulating interest until a target balance has 26 been reached. 27 @param targetBalance the desired balance 28 */ 29 public void waitForBalance(double targetBalance) 30 { 31 while (balance < targetBalance) 32 { 33 year++; 34 double interest = balance * rate / 100; 35 balance = balance + interest; 36 } 37 } 38 Continued

70 Copyright © 2014 by John Wiley & Sons. All rights reserved.70 39 /** 40 Keeps accumulating interest for a given number of years. 41 @param numberOfYears the number of years to wait 42 */ 43 public void waitYears(int numberOfYears) 44 { 45 for (int i = 1; i <= numberOfYears; i++) 46 { 47 double interest = balance * rate / 100; 48 balance = balance + interest; 49 } 50 year = year + n; 51 } 52 53 /** 54 Gets the current investment balance. 55 @return the current balance 56 */ 57 public double getBalance() 58 { 59 return balance; 60 } 61 Continued

71 Copyright © 2014 by John Wiley & Sons. All rights reserved.71 62 /** 63 Gets the number of years this investment has accumulated 64 interest. 65 @return the number of years since the start of the investment 66 */ 67 public int getYears() 68 { 69 return year; 70 } 71 }

72 Copyright © 2014 by John Wiley & Sons. All rights reserved.72  Testing waitYears method: public class InvestmentTester { public static void main(String[] args) { final double INITIAL_BALANCE = 10000; final double RATE = 5; final int YEARS = 20; Investment invest = new Investment(INITIAL_BALANCE, RATE); invest.waitYears(YEARS); double balance = invest.getBalance(); System.out.printf("The balance after %d years is %.2f\n", YEARS, balance); }

73 Copyright © 2014 by John Wiley & Sons. All rights reserved.73 The for Loop Examples

74 Copyright © 2014 by John Wiley & Sons. All rights reserved.74 The do Loop  Executes the body of a loop at least once and performs the loop test after the body is executed.  Used for input validation To force the user to enter a value less than 100 int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); }while (value >= 100);

75 Copyright © 2014 by John Wiley & Sons. All rights reserved.75 Nested Loops  One loop inside another loop.  E.g for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++){ System.out.println(“i=“ +i+ “j=”+j); } }

76 Copyright © 2014 by John Wiley & Sons. All rights reserved.76 Question  What is the output of the following nested for loop: for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(“*"); } System.out.println(); }

77 Copyright © 2014 by John Wiley & Sons. All rights reserved.77 Answer  Output: * ** *** **** ***** ****** for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(“*"); } System.out.println(); }

78 Copyright © 2014 by John Wiley & Sons. All rights reserved.78 Nested Loop Examples

79 Copyright © 2014 by John Wiley & Sons. All rights reserved.79 Nested Loop Examples

80 Copyright © 2014 by John Wiley & Sons. All rights reserved.80 Read Common loop algorithms

81 Copyright © 2014 by John Wiley & Sons. All rights reserved.81 Common Loop Algorithm: Counting Matches  Count how many spaces are in a string: int spaces = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == ' ') { spaces++; } }

82 Copyright © 2014 by John Wiley & Sons. All rights reserved.82 Common Loop Algorithm: Counting Matches  Count how many words in the input have at most three letters: int shortWords = 0; while (in.hasNext()) { String input = in.next(); if (input.length() <= 3) { shortWords++; } }  In a loop that counts matches, a counter is incremented whenever a match is found.

83 Copyright © 2014 by John Wiley & Sons. All rights reserved.83 Common Loop Algorithm: Finding the First Match  Find the first space in a string. Because we do not visit all elements in the string, a while loop is a better choice than a for loop: boolean found = false; char ch = '?’; int position = 0; while (!found && position < str.length()) { ch = str.charAt(position); if (ch == ' ') { found = true; } else { position++; } }  When searching, you look at items until a match is found.

84 Copyright © 2014 by John Wiley & Sons. All rights reserved.84 Common Loop Algorithm: Prompting Until a Match is Found  Keep asking the user to enter a positive value < 100 until the user provides a correct input: boolean valid = false; double input = 0; while (!valid) { System.out.print("Please enter a positive value < 100: "); input = in.nextDouble(); if (0 < input && input < 100) { valid = true; } else { System.out.println("Invalid input."); } }  The variable input is declared outside the while loop because you will want to use the input after the loop has finished.

85 Copyright © 2014 by John Wiley & Sons. All rights reserved.85 Common Loop Algorithm: Maximum and Minimum  To find the largest value, update the largest value seen so far whenever you see a larger one. double largest = in.nextDouble(); while (in.hasNextDouble()) { double input = in.nextDouble(); if (input > largest) { largest = input; } }

86 Copyright © 2014 by John Wiley & Sons. All rights reserved.86 Common Loop Algorithm: Maximum and Minimum  To find the smallest value, reverse the comparison. double smallest = in.nextDouble(); while (in.hasNextDouble()) { double input = in.nextDouble(); if (input < smallest) { smallest = input; } }  There must be at least one input

87 Copyright © 2014 by John Wiley & Sons. All rights reserved.87 Common Loop Algorithm: Comparing Adjacent Values  Check whether a sequence of inputs contains adjacent duplicates such as 1 7 2 9 9 4 9: double input = 0; while (in.hasNextDouble()) { double previous = input; input = in.nextDouble(); if (input == previous) { System.out.println("Duplicate input"); } }  When comparing adjacent values, store the previous value in a variable.


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations."

Similar presentations


Ads by Google