Download Slide 1

Document related concepts
no text concepts found
Transcript
Decisions and Iterations
Copyright © 2014 by John Wiley & Sons. All rights reserved.
1
Chapter Goals





To
To
To
To
To
implement decisions using if statements
implement while, for, and do loops
understand nested loops
develop strategies for testing your programs
validate user input
Copyright © 2014 by John Wiley & Sons. All rights reserved.
2
Decisions
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
4
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
5
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
6
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
6 == 2

6 != 2

2 == 2

2 != 2

the equality operators:
false
true
true
false
Copyright © 2014 by John Wiley & Sons. All rights reserved.
7
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
2 == 2.1
 true
 false
Copyright © 2014 by John Wiley & Sons. All rights reserved.
8
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
9
Logical Operators

You often need to combine the results of comparisons when making
complex decisions

The && operator is called and
•

The || operator is called or
•

Yields the result true if at least one of the conditions is true.
The ! Operator is called not
•


Yields true only when both conditions are true.
Yields negation
! is a unary operator. && and || are binary operators.
All logical operators expect boolean operands and produce boolean results.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
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
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
Logical Operators
Copyright © 2014 by John Wiley & Sons. All rights reserved.
12
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)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
13
Precedence and Associativity of operators
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Java Bitwise operators
 bitwise operators operate on individual bits of integer (int and
long) values
 E.g.
public class Test {
public
int
int
int
static void main(String args[]) {
a = 60; /* 60 = 0011 1100 */
b = 13; /* 13 = 0000 1101 */
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 );
Output:
}
}
From : http://www.tutorialspoint.com/java/java_bitwise_operators_examples.htm
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 < b && c >= d && e == f
as
((a < b) && (c >= d)) && (e == f)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
The if Statement
 The if statement allows a program to test a condition
if(BooleanExpression)
statement;
E.g.
int actualFloor = floor;
OR
if(BooleanExpression) {
statement1;
statement2;
...
}
Block:
Set of
statements
within curly
braces
if (floor > 13)
{
actualFloor--;
}
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
The if-else Statement
 Flowchart with two branches:
E.g.
if(BooleanExpression)
statement or block 1
else
statement or block 2
int actualFloor = floor;
if (floor > 13){
actualFloor--;
}
else{
actualFloor = floor;
}
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
18
The if-else if Statement

Test a series of conditions (multiple alternatives)
if (BooleanExpression1)
statement or block 1
else if(BooleanExpression2)
statement or block 2
else
statement or block 3


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
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
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.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
22
Syntax 5.1 The if Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved.
23
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
Continued
26
System.out.println("The elevator will travel to the actual floor "
27
+ actualFloor);
28
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
29 }
24
section_1/ElevatorSimulation.java
Program Run:
Floor: 20
The elevator will travel to the actual floor 19
Copyright © 2014 by John Wiley & Sons. All rights reserved.
25
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-90
80-89
70-79
<70
A
B
C
D
Sample output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
26
Answer
IfTester.java
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);
}
Copyright
© 2014 by John Wiley & Sons. All rights reserved.
}
27
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
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.
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
Programming Question

Write a class ObjectComparisonTester. Include following code in your main
method to initialize Rectangle objects(java.awt.Rectangle):
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);

Also include statements to test and print if each possible pair of Rectangle
reference variables:
1.
2.

refer to the same Rectangle object in memory and
Refer to Rectangle objects that contain the same content
Sample run is shown:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
31
Answer
ObjectComparisonTester.java
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);
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 ""
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
Relational Operator Examples
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
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)
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
36
Nested Branches
 Example: Federal Income Tax
• Tax depends on marital status and income
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
38
Answer
TaxReturn.java
public class TaxReturn
{
public final int SINGLE = 1;
public final int MARRIED = 2;
private
private
private
private
final
final
final
final
double
double
double
double
RATE1 = 0.10;
RATE2 = 0.25;
RATE1_SINGLE_LIMIT = 32000;
RATE1_MARRIED_LIMIT = 64000;
private double income;
private int status;
TaxReturn(double income, int status)
{
this.income = income;
this.status = status;
}
CONTINUED
Copyright © 2014 by John Wiley & Sons. All rights reserved.
39
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_LIM
}
}
return tax;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
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 Run
Please enter your income: 80000
Are you married? (Y/N) Y
Tax: 10400.0
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
Answer
TaxReturnTester.java
import 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());
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
42
Loops
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
45
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
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.
1
while (condition)
{
2
statements
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
47
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;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
48
Syntax 6.1 while Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
50
Execution of a while Loop

Step by step execution of the investment while loop:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
51
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
52
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Investment.java
/**
A class to monitor the growth of an investment that
accumulates interest at a fixed annual rate.
*/
public class Investment
{
private double balance;
private double rate;
private int year;
/**
Constructs an Investment object from a starting balance and
interest rate.
@param aBalance the starting balance
@param aRate the interest rate in percent
*/
public Investment(double aBalance, double aRate)
{
balance = aBalance;
rate = aRate;
year = 0;
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
53
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
Keeps accumulating interest until a target balance has
been reached.
@param targetBalance the desired balance
*/
public void waitForBalance(double targetBalance)
{
while (balance < targetBalance)
{
year++;
double interest = balance * rate / 100;
balance = balance + interest;
}
}
/**
Gets the current investment balance.
@return the current balance
*/
public double getBalance()
{
return balance;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
54
48
49
50
51
52
53
54
55
56
57
/**
Gets the number of years this investment has accumulated
interest.
@return the number of years since the start of the investment
*/
public int getYears()
{
return year;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
55
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
56
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
InvestmentTester.java
/**
This program computes how long it takes for an investment
to double.
*/
public class InvestmentTester
{
public static void main(String[] args)
{
final double INITIAL_BALANCE = 10000;
final double RATE = 5;
Investment invest = new Investment(INITIAL_BALANCE, RATE);
invest.waitForBalance(2 * INITIAL_BALANCE);
int years = invest.getYears();
System.out.println("The investment doubled after "
+ years + " years");
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
while Loop Examples
Copyright © 2014 by John Wiley & Sons. All rights reserved.
58
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
59
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
2
3
4
5
6
7
8
9
int n = 1729;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
60
Problem Solving: Hand-Tracing - Step by
Step
 Step 1
 Step 2
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
Problem Solving: Hand-Tracing - Step by
Step
 Step 3
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
Problem Solving: Hand-Tracing - Step by
Step
 Step 4
Copyright © 2014 by John Wiley & Sons. All rights reserved.
63
Problem Solving: Hand-Tracing - Step by
Step
 Step 5
Copyright © 2014 by John Wiley & Sons. All rights reserved.
64
Problem Solving: Hand-Tracing - Step by
Step
 Step 6
Copyright © 2014 by John Wiley & Sons. All rights reserved.
65
Problem Solving: Hand-Tracing - Step by
Step
 Step 7
Copyright © 2014 by John Wiley & Sons. All rights reserved.
66
Problem Solving: Hand-Tracing - Step by
Step
 Step 8
Copyright © 2014 by John Wiley & Sons. All rights reserved.
67
Problem Solving: Hand-Tracing - Step by
Step
 Step 9
 Step 10
The sum, which is 19, is printed
Copyright © 2014 by John Wiley & Sons. All rights reserved.
68
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);
}
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
69
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
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
70
Syntax 6.2 for Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved.
71
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
72
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
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
73
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
74
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.
public void waitYears(int numberOfYears)
 Hint: use a for loop to accumulate interest
Copyright © 2014 by John Wiley & Sons. All rights reserved.
75
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Investment.java
/**
A class to monitor the growth of an investment that
accumulates interest at a fixed annual rate
*/
public class Investment
{
private double balance;
private double rate;
private int year;
/**
Constructs an Investment object from a starting balance and
interest rate.
@param aBalance the starting balance
@param aRate the interest rate in percent
*/
public Investment(double balance, double rate)
{
this.balance = balance;
this.rate = rate;
this.year = 0;
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
76
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
Keeps accumulating interest until a target balance has
been reached.
@param targetBalance the desired balance
*/
public void waitForBalance(double targetBalance)
{
while (balance < targetBalance)
{
year++;
double interest = balance * rate / 100;
balance = balance + interest;
}
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
77
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
Keeps accumulating interest for a given number of years.
@param numberOfYears the number of years to wait
*/
public void waitYears(int numberOfYears)
{
for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
year = year + n;
}
/**
Gets the current investment balance.
@return the current balance
*/
public double getBalance()
{
return balance;
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
78
62
63
64
65
66
67
68
69
70
71
/**
Gets the number of years this investment has accumulated
interest.
@return the number of years since the start of the investment
*/
public int getYears()
{
return year;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
79
 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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
80
The for Loop Examples
Copyright © 2014 by John Wiley & Sons. All rights reserved.
81
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);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
82
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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
83
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();
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
84
Answer
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(“*");
}
System.out.println();
}

Output:
*
**
***
****
*****
******
Copyright © 2014 by John Wiley & Sons. All rights reserved.
85
Nested Loop Examples
Copyright © 2014 by John Wiley & Sons. All rights reserved.
86
Nested Loop Examples
Copyright © 2014 by John Wiley & Sons. All rights reserved.
87
Read
Common loop algorithms
Copyright © 2014 by John Wiley & Sons. All rights reserved.
88
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++;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
89
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
90
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
91
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
92
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
93
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
94
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
95