copyright © 2014 by john wiley & sons. all rights reserved.1 decisions and iterations

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

Upload: lucinda-tyler

Post on 12-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

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

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

Decisions and Iterations

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

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

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

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

Decisions

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

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.

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

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 false5 > 3 true3 > 3 false5 <= 3 false5 >= 3 true3 >= 3 true

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

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 interpreta - b * c < d + eas(a – (b * c)) < (d + e)

Check for precedence with other operators:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

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

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 false6 != 2 true2 == 2 true2 != 2 false

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

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 true2 == 2.1 false

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

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.

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

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

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.

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

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

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

}

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

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

Logical Operators

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

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

Short-Circuit Evaluation

Short-circuit evaluation can save time.

Avoid potential errors.

Both && and || rely on this.

E.g. Behavior of the || operator:Evaluate the left operand. If it’s true, return true. Otherwise, evaluate the right operand. If it’s true, return true; if it’s false, return false.

The following expression tests whether i is not 0 before checking whether j/i is greater than 0:

(i != 0) && (j / i > 0)

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

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

Precedence and Associativity of operators

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

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

Java Bitwise operators bitwise operators operate on individual bits of integer (int and

long) values E.g. public class Test {

public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0;

c = a & b; /* bitwise and 12 = 0000 1100 */ System.out.println("a & b = " + c );

c = a | b; /*bitwise or 61 = 0011 1101 */ System.out.println("a | b = " + c );

c = a ^ b; /*bitwise xor 49 = 0011 0001 */ System.out.println("a ^ b = " + c );

c = ~a; /*inverse bit pattern -61 = 1100 0011 */ System.out.println("~a = " + c );

}}

From : http://www.tutorialspoint.com/java/java_bitwise_operators_examples.htm

Output:

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

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

Precedence and Associativity of And, Or, and Not

The ! operator is right associative.

The && and || operators are left associative.

Java would interpreta < b && c >= d && e == f

as((a < b) && (c >= d)) && (e == f)

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

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

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.

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

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

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

elsestatement or block 2

int actualFloor = floor;

if (floor > 13){ actualFloor--;}else{

actualFloor = floor;}

E.g.

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

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

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

elsestatement or block 3

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

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

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

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

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

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.

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

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

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.

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

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

Syntax 5.1 The if Statement

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

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

section_1/ElevatorSimulation.java 1 import java.util.Scanner; 2 3 /** 4 This program simulates an elevator panel that skips the 13th floor. 5 */ 6 public class ElevatorSimulation 7 { 8 public static void main(String[] args) 9 { 10 Scanner in = new Scanner(System.in); 11 System.out.print("Floor: "); 12 int floor = in.nextInt(); 13 14 // Adjust floor if necessary 15 16 int actualFloor; 17 if (floor > 13) 18 { 19 actualFloor = floor - 1; 20 } 21 else 22 { 23 actualFloor = floor; 24 } 25 26 System.out.println("The elevator will travel to the actual floor " 27 + actualFloor); 28 } 29 }

Continued

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

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

section_1/ElevatorSimulation.java

Program Run:

Floor: 20The elevator will travel to the actual floor 19

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

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

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:• testScore grade• 100-90 A• 80-89 B• 70-79 C• <70 D

Sample output:

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

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

Answerimport 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

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

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

Testing Objects for Equality If x and y are two object variables of the same

type, the expression

x == ytests 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.

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

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

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.

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

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

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

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

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

Programming Question Write a class ObjectComparisonTester. 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);

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

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

AnswerObjectComparisonTester.java

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

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

Object Comparison

Rectangle box1 = new Rectangle(5, 10, 20, 30);Rectangle box2 = box1;Rectangle box3 = new Rectangle(5, 10, 20, 30);

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

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

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 ""

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

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

Relational Operator Examples

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

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

Nested Branches Nested set of statements:

• An if statement inside another E.g.

if(condition1){

if(condition2) //if condition1 is true then test condition2

{//do something (condition1==true and

condition2 ==true)}

}

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

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

Nested Branches Example: Federal Income Tax

• Tax depends on marital status and income

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

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

Programming Question

Write a class TaxReturn.java. The class should define the following:• Constants:

• Two integer constants to represent marital status: SINGLE(=1) and MARRIED(=2)

• Two constants to represent the two tax rates RATE1(=10%) and RATE2(=25%)

• Two constants to define the two rate limits for singles, RATE1_SINGLE_LIMIT (=32000) and married, RATE1_MARRIED_LIMIT (=64000)

• Instance Variables:• Two variables to represent the income and the marital status of

person

• Constructors:• A two argument constructor to initialize the income and the

marital status

• Instance Methods: • Method getTax() that calculates and returns tax amount

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

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

Answerpublic class TaxReturn{ public final int SINGLE = 1; public final int MARRIED = 2;

private final double RATE1 = 0.10; private final double RATE2 = 0.25; private final double RATE1_SINGLE_LIMIT = 32000; private final double RATE1_MARRIED_LIMIT = 64000;

private double income; private int status;

TaxReturn(double income, int status) { this.income = income; this.status = status; }

CONTINUED

TaxReturn.java

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

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

public double getTax() { double tax = 0; if (status == SINGLE) { if (income <= RATE1_SINGLE_LIMIT) { tax = RATE1 * income; } else { tax = (RATE1 * RATE1_SINGLE_LIMIT) + (RATE2 * (income - RATE1_SINGLE_LIMIT)) ; } } else { if (income <= RATE1_MARRIED_LIMIT) { tax = RATE1 * income; } else { tax = (RATE1 * RATE1_MARRIED_LIMIT) + (RATE2 * (income - RATE1_MARRIED_LIMIT)); } }

return tax; }}

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

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

Question

Write a tester program TaxReturnTester to test functionality of TaxReturn class. The program should prompt the user to enter income and marital status and print the tax.

A sample run is shown:

Program RunPlease enter your income: 80000Are you married? (Y/N) YTax: 10400.0

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

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

Answerimport java.util.Scanner;

public class TaxCalculator{ public static void main(String[] args) { final int SINGLE = 1; final int MARRIED = 2; Scanner in = new Scanner(System.in);

System.out.print("Please enter your income: "); double income = in.nextDouble();

System.out.print("Are you married? (Y/N) "); String input = in.next(); int status; if (input.equalsIgnoreCase("Y")) { status = MARRIED;//married } else { status = SINGLE;//single }

TaxReturn aTaxReturn = new TaxReturn(income, status);

System.out.println("Tax:” + aTaxReturn.getTax()); }}

TaxReturnTester.java

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

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

Loops

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

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

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

• For processing input consisting of many data items

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

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

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.

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

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

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.

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

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

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

2

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

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

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 * RATE / 100; balance = balance + interest;}

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

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

Syntax 6.1 while Statement

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

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

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

while (balance < targetBalance){ year++; double interest = balance * RATE / 100; balance = balance + interest;}// interest no longer declared here

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

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

Execution of a while Loop Step by step execution of the investment while loop:

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

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

Programming Question Write a class Investment (Investment.java) with

following:• Instance Variables: balance, rate, year• Constructor: two-argument, initialize balance and rate• 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 the template from handouts folder: /net/people/classes/CS160/handouts/lec03

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

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

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

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

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

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

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

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

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 }

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

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

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

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

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

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

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

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

while Loop Examples

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

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

Common Error: Infinite Loops Example:

• forgetting to update the variable that controls the loopint 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

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

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

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?

1 int n = 1729;2 int sum = 0;3 while (n > 0)4 {5 int digit = n % 10;6 sum = sum + digit;7 n = n / 10;8 }9 System.out.println(sum);

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 1

Step 2

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 3

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 4

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 5

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 6

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 7

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 8

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

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

Problem Solving: Hand-Tracing - Step by Step

Step 9

Step 10The sum, which is 19, is printed

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

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

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 10class ForDemo {

public static void main(String[] args){ for(int i=1; i<11; i++){

System.out.println("Count is: " + i); }

} }

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

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

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 counterwhile (counter <= 10) // Check the counter{ System.out.println(counter); counter++; // Update the counter}

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

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

Syntax 6.2 for Statement

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

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

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.

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

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

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}

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

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

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

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

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

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)

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

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

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

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

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

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

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

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

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

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

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

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 }

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

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

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); } }

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

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

The for Loop Examples

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

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

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);

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

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

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);

}}

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

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

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();

}

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

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

Answer

Output:

*********************

for (int i = 1; i <= 6; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(“*");}System.out.println();

}

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

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

Nested Loop Examples

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

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

Nested Loop Examples

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

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

Read

Common loop algorithms

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

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

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++; }}

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

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

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.

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

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

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.

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

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

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.

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

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

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; }}

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

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

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

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

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

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.