chapter 5 | dr. hala | programming 2
TRANSCRIPT
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
1/44
1
Building Java Programs
Chapter 5:Program Logic and Indefinite Loops
These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2005. They may not be
rehosted, sold, or modified without expressed permission from the authors. All rights reserved.
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
2/44
2
Chapter outline
while loops
special types of loops
fencepost loops
sentinel loops
boolean logic
boolean expressions and variables
logical operators testing for valid user input
generating random numbers
the Random class
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
3/44
3
While loops
suggested reading: 5.1 - 5.2.1
self-checks: #1 - 10
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
4/44
4
Types of loops
definite loop: A loop that executes a known numberof times. The for loops we have seen so far are definite loops. We often
use language like "repeat _ times" or "for each of these things".
Examples:
Repeat these statements 10 times. Repeat these statements ktimes.
Repeat these statements for each odd number between 5 and 27.
indefinite loop: A loop where it is not easilydetermined in advance how many times it will execute. Indefinite loops often keep looping as long as a condition is
true, or until a condition becomes false.
Examples:
Repeat these statements until the user types a valid integer.
Repeat these statements while the number n is not prime.
Repeat these statements until a factor ofn is found.
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
5/44
5
The while loop statement
The while loop is a new loop statement that is wellsuited to writing indefinite loops.
The while loop, general syntax:while () {
;}
Example:
int number = 1;
while (number
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
6/44
6
While loop flow chart
The execution of a while loop can be depicted as the following:
|
V
+---------------+
+------+
| +---------------+ || ^ V
V | +-----------------------------------+
| | | execute the controlled statements |
| | +-----------------------------------+
| ^ |
V | V| | |
| +---
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
7/447
Example while loop
A loop that finds and prints the first factor of a number(other than 1):Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
int number = console.nextInt();
int factor = 2;
while (number % factor != 0) {
factor++;
}
System.out.println("First factor: " + factor);
OUTPUT:Type a number: 49
First factor: 7
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
8/448
Equivalence of for,while loops
Any for loop of the following form:
for (; ; ) {
;}
can be replaced by a while loop of the following form:
;
while () {
;;
}
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
9/449
for/while loop example
What while loop is essentially equivalent to thefollowing for loop?for (int i = 1; i
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
10/4410
While loop problem
Write a piece of Java code that uses a while loop torepeatedly prompt the user to type a number until theuser types a non-negative number, then square it.
Expected output:Type a non-negative integer: -5
Invalid number, try again: -1Invalid number, try again: 11
11 squared is 121
Solution:
System.out.print("Type a non-negative integer: ");int number = console.nextInt();while (number < 0) {
System.out.print("Invalid number, try again: ");number = console.nextInt();
}
int square = number * number;System.out.println(number + " squared is " + square);
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
11/4411
Fencepost loops
suggested reading: 5.2.1
self-checks: #11-12
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
12/4412
The fencepost problem
Problem: Write a static method named printNumbersthat prints each number from 1 to a given maximum,which is passed as a parameter, separated by commas.Assume that the maximum number passed in is greaterthan 0. For example, the method call:printNumbers(5)
should print:
1, 2, 3, 4, 5
Let's write a solution to this problem...
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
13/4413
Flawed solutions
public static void printNumbers(int max) {
for (int i = 1; i
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
14/4414
Fence posts
The problem here is that if we are printing n numbers,we only need n - 1 commas.
This problem is similar to the task of building a fence,where lengths of wire are separated by posts.
If we repeatedly place a post and place a length, wewill never have an end post.
A flawed algorithm:
for (length of fence):
place some post.
place some wire.
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
15/4415
Fencepost solution
The key to solving the fencepost problem is to add anextra statement outside the loop that places the initalpost. This is sometimes also called the "loop-and-a-half" solution.
We will encounter this concept many times in this chapter when
using indefinite while loops. The revised algorithm:
place a post.
for (length of fence - 1):
place some wire.place some post.
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
16/4416
Fencepost printNumbers
A version of printNumbers that works:
public static void printNumbers(int max) {
System.out.print(1);
for (int i = 2; i
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
17/4417
Fencepost practice problem
Write a Java program that reads a base and amaximum power and prints all of the powers of thegiven base up to that max, separated by commas.
Base: 2
Max exponent: 9
The first 9 powers of 2 are:
2, 4, 8, 16, 32, 64, 128, 256, 512
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
18/4418
Fencepost practice problem
Write a method named printFactors that, when given anumber, prints its factors in the following format (usingan example of 24 for the parameter value):
[1, 2, 3, 4, 6, 8, 12, 24]
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
19/4419
Sentinel loops
suggested reading: 5.2.2
self-checks: #13-15
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
20/4420
Sentinel values
sentinel: A special input value that signals the end ofthe user's input.
Example: Write a program that repeatedly prompts the user fornumbers to add until the user types 0, then outputs their sum.
(In this case, the number 0 is our sentinel value.)
Expected output:
Enter a number (0 to quit): 95
Enter a number (0 to quit): 87
Enter a number (0 to quit): 43Enter a number (0 to quit): 29
Enter a number (0 to quit): 0
The total was 254
Let's write it...
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
21/4421
Flawed sentinel solution
What's wrong with this solution?
Scanner console = new Scanner(System.in);
int sum = 0;
int inputNumber = 1; // "dummy value", anything but 0
while (inputNumber != 0) {
System.out.print("Enter a number (0 to quit): ");
inputNumber = console.nextInt();
sum += inputNumber;}
System.out.println("The total was " + sum);
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
22/4422
Changing the sentinel value
To see the problem, change the sentinel's value to -1:Scanner console = new Scanner(System.in);
int sum = 0;
int inputNumber = 1; // "dummy value", anything but -1
while (inputNumber != -1) {
System.out.print("Enter a number (-1 to quit): ");
inputNumber = console.nextInt();
sum += inputNumber;
}
System.out.println("The total was " + sum);
Now the solution produces the wrong output. Why?
The total was 253
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
23/44
23
The problem with our code
Our code uses a pattern like this:sum = 0
while we have not seen the sentinel:
prompt for input, read input.
add input to the sum.
On the last pass through the loop, the sentinel is addedto the sum:
prompt for input, read sentinel of -1.
add -1 to the sum.
This is a fencepost problem! How can we solve it?
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
24/44
24
A fencepost solution
We need the code to use a pattern like this:sum = 0
prompt for input, read inputn.
while n is not the sentinel:
add n to the sum.
prompt for input, read a value into n.
sentinel loop: A loop that successfully navigatesaround a sentinel value related fencepost issue.
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
25/44
25
More correct code
This solution produces the correct output:System.out.print("Enter a number (-1 to quit): ");int inputNumber = console.nextInt();
while (inputNumber != -1) {
sum += inputNumber;
System.out.print("Enter a number (-1 to quit): ");
inputNumber = console.nextInt();
}
System.out.println("The total was " + sum);
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
26/44
26
Even better code
An even better solution creates a constant for the sentinel:public static final int SENTINEL = -1;
This solution uses the constant:System.out.print("Enter a number (" + SENTINEL +
" to quit): ");
int inputNumber = console.nextInt();
while (inputNumber != SENTINEL) {
sum += inputNumber;
System.out.print("Enter a number (" + SENTINEL +" to quit): ");
inputNumber = console.nextInt();
}
System.out.println("The total was " + sum);
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
27/44
27
Boolean logic
suggested reading: 5.3
self-checks: #16-19, 24
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
28/44
28
Type boolean
boolean: Primitive type to represent logical values. A boolean variable can hold one of two values: true or false.
All the s we have used in our if statements andfor loops have been boolean literal values.
It is legal to create boolean variables, pass boolean
parameters, return boolean values from methods, ...
Example:int x = 7;
boolean test1 = true;
boolean test2 = (x < 10); // trueboolean test3 = (x % 2 == 0); // false
if (test2) {
System.out.println("under 10");
}
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
29/44
29
Logical operators && || !
Boolean expressions can be joined together with thefollowing logical operators:
The following 'truth tables' show the effect of eachoperator on any boolean values p and q:
Operator Description Example Result
&& and (9 != 6) && (2 < 3) true
|| or (2 == 3) || (-1 < 5) true
! not !(7 > 0) false
p q p && q p || q
true true true true
true false false true
false true false true
false false false false
p !p
true false
false true
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
30/44
30
Methods that return boolean
There are several methods in Java that return booleanvalues.
A call to one of these methods can be used as a on a for loop, while loop, or if statement.
Examples:
Scanner console = new Scanner(System.in);System.out.print("Type your age or name: ");
if (console.hasNextInt()) {
int age = console.nextInt();
System.out.println("You are " + age + " years old.");
} else {
String line = console.nextLine();if (line.startsWith("Dr.")) {
System.out.println("Will you marry me?");
}
}
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
31/44
31
Testing for valid user input
A Scanner object has methods that can be used to test whether
the upcoming input token is of a given type:
Each of these methods waits for the user to type input tokens andpress Enter, then reports a true or false answer.
The hasNext and hasNextLine methods are not useful until we learnhow to read input from files in Chapter 6.
Method Description
hasNext() Whether or not the next token can be read as aString(always true for console input)
hasNextInt() Whether or not the next token can be read as anint
hasNextDouble() Whether or not the next token can be read as adouble
hasNextLine() Whether or not the next line of input can be readas a String(always true for console input)
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
32/44
32
Scanner condition example
The Scanner's hasNext___ methods are very useful for testing
whether the user typed the right kind of token for our program touse, before we read it (and potentially crash!).
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
if (console.hasNextInt()) {
int age = console.nextInt();
System.out.println("Retire in " + (65 - age) + " years.");
} else {
System.out.println("You did not type an integer.");
}
System.out.print("Type 10 numbers: ");for (int i = 1; i
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
33/44
33
Comparing objects: .equals
The relational operators such as < and == only behave correctly on
primitive values.
Objects such as String, Point, and Color should be compared forequality by calling a method named equals.
Example (incorrect):
String name = console.next();if (name == "Teacher") {
System.out.println("You must be a swell person!");
}
It turns out that this example code will compile, but it will never print themessage. The == operator on Strings usually returns false even when the
Strings have the same letters in them.
Example (correct):String name = console.next();
if (name.equals("Teacher")) {
System.out.println("You must be a swell person!");
}
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
34/44
34
String condition methods
There are several methods of a String object that canbe used as conditions in if statements:
Method Description
equals(String) whether two Strings contain exactly the
same charactersequalsIgnoreCase(String) whether two Strings contain the same
characters, ignoring upper vs. lowercase differences
startsWith(String) whether one String contains the other'scharacters at its start
endsWith(String) whether one String contains the other'scharacters at its end
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
35/44
35
String condition examples
Scanner console = new Scanner(System.in);
System.out.print("Type your full name and title: ");String name = console.nextLine();
if (name.endsWith("Ph. D.")) {
System.out.println("Hello, doctor!");
}if (name.startsWith("Ms.")) {
System.out.println("Greetings, Ma'am.");
}
if (name.equalsIgnoreCase("boss")) {
System.out.println("Welcome, master! Command me!");}
if (name.toLowerCase().indexOf("jr.") >= 0) {
System.out.println("Your parent has the same name!");
}
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
36/44
36
Testing for an input value
When testing user input for a certain String, the == and!= operators will not behave properly. System.out.print("Type OK to draw the badger.");String response = console.next();if (response == "OK") { // wrong
drawBadger();
}
Recall: The relational operators such as < and == onlybehave correctly on primitive values. Objects such as String, Point, and Color can be compared for
equality by calling a method named equals. Corrected code from above:System.out.print("Type OK to draw the badger.");String response = console.next();if (response.equals("OK")) { // better!
drawBadger();
}
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
37/44
37
Boolean practice problem
Write a program that compares two words typed by the user tosee whether they "rhyme" (end with the same last two letters)and/or alliterate (begin with the same letter).
Use methods with return values to tell whether two words rhymeand/or alliterate.
Example:
Type two words: car STARThey rhyme!
(run #2)
Type two words: bare bear
They alliterate!
(run #3)
Type two words: sell shell
They alliterate!
They rhyme!
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
38/44
38
Boolean practice problem
Write a program that reads two numbers from the userand tells whether each is prime, or if not, gives thenext prime after it; also tell whether they are relativelyprime (have no common factors).
Examples:
Type two numbers: 9 169 is not prime; the next prime after 9 is 11
16 is not prime; the next prime after 16 is 17
9 and 16 are relatively prime
(run #2)
Type two numbers: 7 21
7 is prime
21 is not prime; the next prime after 21 is 23
7 and 21 are not relatively prime
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
39/44
39
Generating random numbers
suggested reading: 5.2.4
self-checks: #20-23
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
40/44
40
The Random class
Java has a class named Random whose objectsgenerate pseudo-random numbers.
Example:
Random rand = new Random();int randomNumber = rand.nextInt(10);
// randomNumber has a random value between 0 and 9
Class Random is found in the java.util package.
import java.util.*;
Method name Description
nextInt() returns a random integer
nextInt(max) returns a random integer in the range [0, max)in other words, from 0 up through one less than the max
nextDouble() returns a random real number in the range [0.0, 1.0)
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
41/44
41
Random examples
Random rand = new Random();
A random number between 0 and 19 inclusive:
A random number between 1 and 10 inclusive:
A random number between 4 and 17 inclusive:
A random even number between 0 and 10 inclusive:
A random multiple of 10 between 100 and 200 inclus.:
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
42/44
42
Random examples (answers)
Random rand = new Random();
A random number between 0 and 19 inclusive:int random1 = rand.nextInt(20);
A random number between 1 and 10 inclusive:int random1 = rand.nextInt(10) + 1;
A random number between 4 and 17 inclusive:int random1 = rand.nextInt(14) + 4;
A random even number between 0 and 10 inclusive:int random1 = rand.nextInt(6) * 2;
A random multiple of 10 between 100 and 200 inclus.:
int random1 = rand.nextInt(11) * 10 + 100;
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
43/44
43
Random practice problem
Write a multiplication tutor program. Example dialogue:This program helps you learn multiplication byAsking you 5 random multiplication questionsand counts how many you get right.
#1 of 5: 10 * 25 = 250Correct!
#2 of 5: 72 * 12 = 864Correct!
#3 of 5: 87 * 21 = 1741Incorrect. The correct answer was 1827
#4 of 5: 8 * 84 = 692Incorrect. The correct answer was 672
#5 of 5: 25 * 36 = 900Correct!
You got 3 out of 5
-
8/2/2019 Chapter 5 | Dr. Hala | Programming 2
44/44
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 ofwhether the condition is true.
The do/while loop, general syntax:do {
;} while ();
Example:// roll until we get a number other than 3Random rand = new Random();
int dice;
do {
dice = rand.nextInt();