Transcript ch05-3

Indefinite loop variations

suggested reading: 5.4
1
The do/while loop

Java has another kind of loop named the do/while loop.


It is almost identical to the while loop, except that its body
statement(s) will always execute the first time, regardless of
whether the condition is true.
The do/while loop, general syntax:
do {
<statement(s)> ;
} while (<condition>);

Example:
// roll until we get a number other than 3
Random rand = new Random();
int dice;
do {
dice = rand.nextInt();
} while (dice == 3);
2
do/while loop flow chart
3
"Forever" loop with break

break statement: Immediately exits a loop when
reached.



Can be used to write a loop whose test is in the middle.
Such loops are often called "forever" loops because their
header's boolean test is often changed to a trivial true.
"forever" loop, general syntax:
while (true) {
<statement(s)> ;
if (<condition>) {
break;
}
<statement(s)> ;
}
4
More correct code

This code correctly implements a sentinel loop:
int sum = 0;
while (true) {
System.out.print("Enter a number (-1 to quit): ");
int inputNumber = console.nextInt();
if (inputNumber == -1) {
break;
}
sum += inputNumber;
// inputNumber != -1 here
}
System.out.println("The total was " + sum);
5
Random/while question

Write a multiplication tutor program. Example log of execution:
This program helps you practice multiplication
by asking you random multiplication questions
with numbers ranging from 1 to 20
and counting how many you solve correctly.
14 * 8 = 112
Correct!
5 * 12 = 60
Correct!
8 * 3 = 24
Correct!
5 * 5 = 25
Correct!
20 * 14 = 280
Correct!
19 * 14 = 256
Incorrect; the correct answer was 266
You solved 5 correctly.

Use a class constant for the maximum value of 20.
6
User errors

suggested reading: 5.3
7
Testing for valid user input

A Scanner object has methods that can be used to "look ahead" to
test whether the upcoming input token is of a given type:
Method
Description
hasNext()
Whether or not the next token can be read as a
String (always true for console input)
hasNextInt()
Whether or not the next token can be read as an
int
hasNextDouble()
Whether or not the next token can be read as a
double
hasNextLine()
Whether or not the next line of input can be read
as a String (always true for console input)

Each of these methods waits for the user to type input tokens and
press Enter, then reports a true or false answer.

The hasNext and hasNextLine methods are not useful until we learn
how to read input from files in Chapter 6.
8
Scanner condition example

The Scanner's hasNext methods are useful for testing whether the
user typed the right kind of token for our program to use, before
we read it (and potentially cause an exception!).
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
if (console.hasNextInt()) {
int age = console.nextInt();
// will not throw an exception
System.out.println("Retire in " + (65 - age) + " years.");
} else if (console.hasNextDouble()) {
System.out.println("Please use a whole number for your age!");
} else {
System.out.println("You did not type a number.");
}
9
Assertions

suggested reading: 5.5
10
Logical assertions

assertion: A declarative statement that is either true
or false.
Examples:
 Java was created in 1995.
 The sky is purple.
 7 is a prime number.
 10 > 20.
 x % 2 == 0. (depends on the value of x)
11
Assertions in code

We can make assertions about our code and ask
whether they are true at various points in the code.

Valid answers are ALWAYS, NEVER, or SOMETIMES.
System.out.print("Type a nonnegative number: ");
double number = console.nextDouble();
// Point A: is number < 0.0 here?
while (number < 0.0) {
// Point B: is number < 0.0 here?
System.out.print("Negative; try again: ");
number = console.nextDouble();
// Point C: is number < 0.0 here?
}
// Point D: is number < 0.0 here?
12
Assertions in code answers

We can make assertions about our code and ask
whether they are true at various points in the code.

Valid answers are ALWAYS, NEVER, or SOMETIMES.
System.out.print("Type a nonnegative number: ");
double number = console.nextDouble();
// Point A: is number < 0.0 here?
(SOMETIMES)
while (number < 0.0) {
// Point B: is number < 0.0 here?
(ALWAYS)
System.out.print("Negative; try again: ");
number = console.nextDouble();
// Point C: is number < 0.0 here?
(SOMETIMES)
}
// Point D: is number < 0.0 here?
(NEVER)
13
Assertion example 1
public static int mystery(Scanner console) {
int prev = 0;
int count = 0;
int next = console.nextInt();
// Point A
while (next != 0) {
// Point B
if (next == prev) {
// Point C
Which of the following assertions are true
count++;
at which point(s) in the code?
}
Choose ALWAYS, NEVER, or SOMETIMES.
prev = next;
next = console.nextInt();
// Point D
next == 0 prev == 0 next == prev
}
Point A
// Point E
return count;
Point B
}
Point C
Point D
Point E
14
Assertion example 1 answer
public static int mystery(Scanner console) {
int prev = 0;
int count = 0;
int next = console.nextInt();
// Point A
while (next != 0) {
// Point B
if (next == prev) {
// Point C
Which of the following assertions are true
count++;
at which point(s) in the code?
}
Choose ALWAYS, NEVER, or SOMETIMES.
prev = next;
next = console.nextInt();
// Point D
next == 0 prev == 0 next == prev
}
SOMETIMES
Point A SOMETIMES ALWAYS
// Point E
return count;
SOMETIMES SOMETIMES
Point B NEVER
}
Point C
NEVER
NEVER
ALWAYS
Point D
SOMETIMES
NEVER
SOMETIMES
Point E
ALWAYS
SOMETIMES
SOMETIMES
15
Assertion example 2
public static void mystery(int x, int y) {
int z = 0;
// Point A
while (x >= y) {
// Point B
x -= y;
// Point C
z++;
// Point D
Which of the following assertions are true
at which point(s) in the code?
Choose ALWAYS, NEVER, or SOMETIMES.
}
}
// Point E
System.out.println(z + Point A
" " + x);
Point B
x < y
x == y
z == 0
Point C
Point D
Point E
16
Assertion example 2 answer
public static void mystery(int x, int y) {
int z = 0;
// Point A
while (x >= y) {
// Point B
x -= y;
// Point C
z++;
// Point D
Which of the following assertions are true
at which point(s) in the code?
Choose ALWAYS, NEVER, or SOMETIMES.
}
}
// Point E
System.out.println(z + Point A
" " + x);
x < y
x == y
z == 0
SOMETIMES
SOMETIMES
ALWAYS
Point B
NEVER
SOMETIMES
SOMETIMES
Point C
SOMETIMES
SOMETIMES
SOMETIMES
Point D
SOMETIMES
SOMETIMES
NEVER
Point E
ALWAYS
NEVER
SOMETIMES
17
Assertion example 3
// pre : y >= 0,
post: returns x^y
public static int pow(int x, int y) {
int prod = 1;
// Point A
while (y > 0) {
// Point B
if (y % 2 == 0) {
// Point C
x *= x;
y /= 2;
// Point D
} else {
// Point E
prod *= x;
y--;
// Point F
}
// Point G
}
// Point H
return prod;
}
Which of the following assertions are true
at which point(s) in the code?
Choose ALWAYS, NEVER, or SOMETIMES.
y == 0
y % 2 == 0
Point A
Point B
Point C
Point D
Point E
Point F
Point G
Point H
18
Assertion example 3 answer
// pre : y >= 0,
post: returns x^y
public static int pow(int x, int y) {
int prod = 1;
// Point A
while (y > 0) {
// Point B
if (y % 2 == 0) {
// Point C
x *= x;
y /= 2;
// Point D
} else {
// Point E
prod *= x;
y--;
// Point F
}
// Point G
}
// Point H
return prod;
}
Which of the following assertions are true
at which point(s) in the code?
Choose ALWAYS, NEVER, or SOMETIMES.
y == 0
y % 2 == 0
Point A
SOMETIMES
SOMETIMES
Point B
NEVER
SOMETIMES
Point C
NEVER
ALWAYS
Point D
NEVER
SOMETIMES
Point E
NEVER
NEVER
Point F
SOMETIMES
ALWAYS
Point G
SOMETIMES
SOMETIMES
Point H
ALWAYS
ALWAYS
19