Download lecture4

Document related concepts
no text concepts found
Transcript
Programming Fundamentals I (COSC1336),
Lecture 4 (prepared after Chapter 4 of
Liang’s 2011 textbook)
Stefan Andrei
5/9/2017
COSC-1336, Lecture 4
1
Overview of Previous Lecture
declare boolean type and write Boolean expressions using
comparison operators (§3.2).
 To program AdditionQuiz using Boolean expressions (§3.3).
 To implement selection control using one-way if statements
(§3.4)
 To program the GuessBirthday game using one-way if
statements (§3.5).
 To implement selection control using two-way if statements
(§3.6).
 To implement selection control using nested if statements (§3.7).
 To avoid common errors in if statements (§3.8).
 To
 To
program using selection statements for a variety of examples
(SubtractionQuiz) (§3.9-3.11).
5/9/2017
COSC-1336, Lecture 4
2
Overview of Previous Lecture (cont)
combine conditions using logical operators (&&, ||, and !)
(§3.12).
 To program using selection statements with combined conditions
(LeapYear, Lottery) (§§3.13-3.14).
 To implement selection control using switch statements
(§3.15).
 To write expressions using the conditional operator (§3.16).
 To format output using the System.out.printf() method and
to format strings using the String.format() method (§3.17).
 To
 To
examine the rules governing operator precedence and
associativity (§3.18).
 (GUI) To get user confirmation using confirmation dialogs
(§3.19).
5/9/2017
COSC-1336, Lecture 4
3
Motivation of the current lecture
Suppose that you need to print a String (e.g.,
"Welcome to Java!") a hundred times.
 It would be tedious to have to write the
following statement a hundred times:

System.out.println("Welcome to Java!");

So, how do you solve this problem?
5/9/2017
COSC-1336, Lecture 4
4
Opening Problem
Problem:
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
100
times
to
to
to
to
to
to
Java!");
Java!");
Java!");
Java!");
Java!");
Java!");
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
5/9/2017
COSC-1336, Lecture 4
5
Introducing while Loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
5/9/2017
COSC-1336, Lecture 4
6
Overview of This Lecture







5/9/2017
To write programs for executing statements
repeatedly using a while loop (§4.2).
To develop a program for GuessNumber and
SubtractionQuizLoop (§4.2.1).
To follow the loop design strategy to develop loops
(§4.2.2).
To develop a program for SubtractionQuizLoop
(§4.2.3).
To control a loop with a sentinel value (§4.2.3).
To obtain large input from a file using input
redirection rather than typing from keyboard (§4.2.4).
To write loops using do-while statements (§4.3).
COSC-1336, Lecture 4
7
Overview of This Lecture (cont.)







To write loops using for statements (§4.4).
To discover the similarities and differences of three
types of loop statements (§4.5).
To write nested loops (§4.6).
To learn the techniques for minimizing numerical
errors (§4.7).
To learn loops from a variety of examples (GCD,
FutureTuition, MonteCarloSimulation) (§4.8).
To implement program control with break and continue
(§4.9).
(GUI) To control a loop with a confirmation dialog
(§4.10).
5/9/2017
COSC-1336, Lecture 4
8
while
Loop Flow Chart
while (loop-continuation-condition)
{
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
// loop-body;
count++;
Statement(s);
}
}
count = 0;
Loop
Continuation
Condition?
false
(count < 100)?
true
Statement(s)
(loop body)
true
System.out.println("Welcome to Java!");
count++;
(B)
(A)
5/9/2017
false
COSC-1336, Lecture 4
9
animation
Trace while Loop
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
10
animation
Trace while Loop, cont.
(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
11
animation
Trace while Loop (cont.)
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
12
animation
Trace while Loop (cont.)
Increase count by 1
count is 1 now
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
13
animation
Trace while Loop (cont.)
(count < 2) is still true since
count is 1
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
14
animation
Trace while Loop (cont.)
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
15
animation
Trace while Loop (cont.)
Increase count by 1
count is 2 now
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
16
animation
Trace while Loop (cont.)
(count < 2) is false since
count is 2 now
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
17
animation
Trace while Loop
The loop exits. Execute the next
statement after the loop.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
5/9/2017
COSC-1336, Lecture 4
18
Problem: Guessing Numbers



Write a program that randomly generates an
integer between 0 and 100, inclusive.
The program prompts the user to enter a
number continuously until the number
matches the randomly generated number.
For each user input, the program tells the
user whether the input is too low or too high,
so the user can choose the next input
intelligently.
5/9/2017
COSC-1336, Lecture 4
19
GuessNumber.java
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number
between 0 and 100");
int guess = -1;
. . . // the while loop is next slide . . .
}
}
5/9/2017
COSC-1336, Lecture 4
20
The while loop of the previous program
while (guess != number) {
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
guess = input.nextInt();
if (guess == number)
System.out.println("Yes, the number is " +
number);
else
if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
5/9/2017
COSC-1336, Lecture 4
21
Compiling and running
GuessNumber.java
5/9/2017
COSC-1336, Lecture 4
22
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed
is not predetermined.
 You may use an input value to signify the end
of the loop.
 Such a value is known as a sentinel value.
 Write a program that reads and calculates the
sum of an unspecified number of integers.
 The input 0 signifies the end of the input.

5/9/2017
COSC-1336, Lecture 4
23
SentinelValue.java
import java.util.Scanner;
public class SentinelValue { /** Main method */
public static void main(String[] args) {
// Create a Scanner Scanner
input = new Scanner(System.in);
// Read an initial data
System.out.print( "Enter an int value (the program
exits if the input is 0): ");
int data = input.nextInt();
// Keep reading data until the input is 0
int sum = 0;
. . . // the while loop is next slide . . .
System.out.println("The sum is " + sum);
}
}
5/9/2017
COSC-1336, Lecture 4
24
The while loop of the previous program
while (data != 0) {
sum += data;
// Read the next data
System.out.print("Enter an int value (the
program exits if the input is 0): ");
data = input.nextInt();
}
5/9/2017
COSC-1336, Lecture 4
25
Compiling and running
SentinelValue.java
5/9/2017
COSC-1336, Lecture 4
26
Caution
Don’t use floating-point values for equality checking in a
loop control.
 Since floating-point values are approximations for some
values, using them could result in imprecise counter
values and inaccurate results.
 Consider the following code for computing 1 + 0.9 + 0.8
+ ... + 0.1:

double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
System.out.println(sum);
5/9/2017
COSC-1336, Lecture 4
27
Explanations about previous code




Variable item starts with 1 and is reduced by 0.1
every time the loop body is executed.
The loop should terminate when item becomes 0.
However, there is no guarantee that item will be
exactly 0, because the floating-point arithmetic is
approximated.
This loop seems OK on the surface, but it is actually
an infinite loop.
5/9/2017
COSC-1336, Lecture 4
28
do-while
Loop
Statement(s)
(loop body)
true
Loop
Continuation
Condition?
do {
false
// Loop body;
Statement(s);
} while (loop-continuation-condition);
5/9/2017
COSC-1336, Lecture 4
29
for
Loops
int i;
for (initial-action; loopfor (i = 0; i < 100; i++) {
continuation-condition;
System.out.println(
action-after-each-iteration)
"Welcome to Java!");
{
}
// loop body;
Statement(s);
}
Initial-Action
i=0
Loop
Continuation
Condition?
5/9/2017
false
(i < 100)?
true
Statement(s)
(loop body)
true
System.out.println(
"Welcome to Java");
Action-After-Each-Iteration
i++
(A)
(B)
COSC-1336, Lecture 4
false
30
animation
Trace for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
Declare i
31
animation
Trace for Loop (cont.)
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
Execute initializer
i is now 0
32
animation
Trace for Loop (cont.)
(i < 2) is true
since i is 0
int i;
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
33
animation
Trace for Loop (cont.)
Print Welcome to Java!
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
34
animation
Trace for Loop (cont.)
Execute adjustment statement
i now is 1
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
35
animation
Trace for Loop (cont.)
(i < 2) is still true
since i is 1
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
36
animation
Trace for Loop (cont.)
Print Welcome to Java!
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
37
animation
Trace for Loop (cont.)
Execute adjustment statement
i now is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
38
animation
Trace for Loop (cont.)
(i < 2) is false
since i is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
39
animation
Trace for Loop (cont.)
Exit the loop. Execute the next
statement after the loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
5/9/2017
COSC-1336, Lecture 4
40
Note 1
 The initial-action in a for loop can be a list of zero
or more comma-separated expressions.
 The action-after-each-iteration in a for loop can be
a list of zero or more comma-separated statements.
 Therefore, the following two for loops are correct.
 They are rarely used in practice, however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
5/9/2017
COSC-1336, Lecture 4
41
Note 2
 If the loop-continuation-condition in a for loop is
omitted, it is implicitly true.
 Thus the statement given below in (a), which is an
infinite loop, is correct.
 Nevertheless, it is better to use the equivalent loop
in (b) to avoid confusion:
for ( ; ; ) {
// Do something
}
Equivalent
(a)
5/9/2017
while (true) {
// Do something
}
(b)
COSC-1336, Lecture 4
42
Caution
Adding a semicolon at the end of the for clause
before the loop body is a common mistake, as
shown below:
Logic

Error
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}
5/9/2017
COSC-1336, Lecture 4
43
Caution (cont.)

Similarly, the following loop is also wrong:
int i=0;
Logic Error
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following
semicolon is needed to end the loop.

int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10);
Correct
5/9/2017
COSC-1336, Lecture 4
44
Which Loop to Use?
 The three forms of loop statements, while, do-while, and for,
are expressively equivalent; that is, you can write a loop in any of
these three forms.
 For example, a while loop in (a) in the following figure can
always be converted into the following for loop in (b):
while (loop-continuation-condition) {
// Loop body
}
for ( ; loop-continuation-condition; )
// Loop body
}
Equivalent
(a)
(b)
 A for loop in (a) in the following figure can generally be
converted into the following while loop in (b) except in certain
special cases (see Review Question 3.19 for one of them):
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
Equivalent
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
(a)
5/9/2017
(b)
COSC-1336, Lecture 4
45
Recommendations
 Use the one that is most intuitive and comfortable for
you.
 In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times.
 A while loop may be used if the number of repetitions
is not known, as in the case of reading the numbers until
the input is 0.
 A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition.
5/9/2017
COSC-1336, Lecture 4
46
Minimizing Numerical Errors
Numeric errors involving floating-point
numbers are inevitable.
 Here is an example that sums a series that
starts with 0.01 and ends with 1.0.
 The numbers in the series will increment by
0.01, as follows: 0.01 + 0.02 + 0.03 and so on.

5/9/2017
COSC-1336, Lecture 4
47
TestSum.java
public class TestSum {
public static void main(String[] args) {
// Initialize sum
float sum = 0;
// Add 0.01, 0.02, ..., 0.99, 1 to sum
for (float i = 0.01f; i <= 1.0f; i = i + 0.01f)
sum += i;
// Display result
System.out.println("The sum is " + sum);
}
}
5/9/2017
COSC-1336, Lecture 4
48
Compiling and running TestSum.java
5/9/2017
COSC-1336, Lecture 4
49
Problem: Finding the Greatest
Common Divisor


Problem: Write a program that prompts the user
to enter two positive integers and finds their
greatest common divisor.
Examples:



Suppose you enter two integers 4 and 2, their
greatest common divisor is 2.
Suppose you enter two integers 16 and 24, their
greatest common divisor is 8.
So, how do you find the greatest common
divisor?
5/9/2017
COSC-1336, Lecture 4
50
The main idea



Let the two input integers be n1 and n2.
You know number 1 is a common divisor, but
it may not be the greatest commons divisor.
So you can check whether k (for k = 2, 3, 4,
and so on) is a common divisor for n1 and n2,
until k is greater than n1 or n2.
5/9/2017
COSC-1336, Lecture 4
51
GreatestCommonDivisor.java
import java.util.Scanner;
public class GreatestCommonDivisor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
int gcd = 1, k = 2;
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0) gcd = k;
k++;
}
System.out.println("The greatest common divisor for " +
n1 + " and " + n2 + " is " + gcd);
}
}
5/9/2017
COSC-1336, Lecture 4
52
Compiling and running
GreatestCommonDivisor.java
5/9/2017
COSC-1336, Lecture 4
53
EuclidGreatestCommonDivisor.java
import java.util.Scanner;
public class EuclidGreatestCommonDivisor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
int gcd, div1;
// . . . The while loop is on the next slide . . .
System.out.println(n1);
}
}
5/9/2017
COSC-1336, Lecture 4
54
The do-while loop
System.out.println("The greatest common divisor for "
+ n1 + " and " + n2 + " is ");
int aux;
do {
if (n1 < n2) {
aux = n1;
n1 = n2;
n2 = aux;
}
div1 = n1 % n2;
n1 = n2;
n2 = div1;
}
while (div1 != 0);
5/9/2017
COSC-1336, Lecture 4
55
Compiling and running
EuclidGreatestCommonDivisor.java
5/9/2017
COSC-1336, Lecture 4
56
The break statement inside while loops

The break statement causes the while loop to
terminate and execution continues from the next
statement after the while loop.
int count = 0;
while (count <= 25) {
count = count + 1;
if (count == 10) break;
System.out.println(count);
}

The above while statement will display 1, 2, …,
and then continue with the next statement that
follow the while loop.
5/9/2017
COSC-1336, Lecture 4
9
57
TestBreak.java
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100) break;
}
System.out.println("The number is " + number);
System.out.println("The sum is " + sum);
}
}
5/9/2017
COSC-1336, Lecture 4
58
Compiling and running TestBreak.java
5/9/2017
COSC-1336, Lecture 4
59
The continue statement inside while
loops

The continue statement causes the statements that
follow in the while loop to be skipped and the
condition of the while loop is evaluated again.
int count = 0;
while (count <= 25) {
count = count + 1;
if (count == 10) continue;
System.out.println(count);
}

The above while statement will display 1, 2, …, 9,
11, …, 26 and (note that 10 is missing) then continue
with the next statement that follow the while loop.
5/9/2017
COSC-1336, Lecture 4
60
TestContinue.java
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11) continue;
sum += number;
}
System.out.println("The sum is " + sum);
}
}
5/9/2017
COSC-1336, Lecture 4
61
Compiling and running
TestContinue.java
5/9/2017
COSC-1336, Lecture 4
62
(GUI) Controlling a Loop with a
Confirmation Dialog
 A sentinel-controlled loop can be implemented using a
confirmation dialog.
 The answers Yes or No to continue or terminate the loop.
 The template of the loop may look as follows:
int option = 0;
while (option == JOptionPane.YES_OPTION) {
System.out.println("continue loop");
option = JOptionPane.showConfirmDialog(null, "Continue?");
}
5/9/2017
COSC-1336, Lecture 4
63
SentinelValueUsingConfirmation
Dialog.java
import javax.swing.JOptionPane;
public class SentinelValueUsingConfirmationDialog {
public static void main(String[] args) {
int sum = 0, option = 0;
while (option == JOptionPane.YES_OPTION) {
String dataString = JOptionPane.showInputDialog(
"Enter an int value: ");
int data = Integer.parseInt(dataString);
sum += data;
option = JOptionPane.showConfirmDialog(null,
"Continue?");
}
JOptionPane.showMessageDialog(null, "The sum is " + sum);
}
}
5/9/2017
COSC-1336, Lecture 4
64
Compiling and running SentinelValue
UsingConfirmationDialog.java
5/9/2017
COSC-1336, Lecture 4
65
Running SentinelValueUsing
ConfirmationDialog.java
5/9/2017
COSC-1336, Lecture 4
66
Running SentinelValueUsing
ConfirmationDialog.java
5/9/2017
COSC-1336, Lecture 4
67
Running SentinelValueUsing
ConfirmationDialog.java
5/9/2017
COSC-1336, Lecture 4
68
Running SentinelValueUsing
ConfirmationDialog.java
5/9/2017
COSC-1336, Lecture 4
69
Summary







5/9/2017
To write programs for executing statements
repeatedly using a while loop (§4.2).
To develop a program for GuessNumber and
SubtractionQuizLoop (§4.2.1).
To follow the loop design strategy to develop loops
(§4.2.2).
To develop a program for SubtractionQuizLoop
(§4.2.3).
To control a loop with a sentinel value (§4.2.3).
To obtain large input from a file using input
redirection rather than typing from keyboard (§4.2.4).
To write loops using do-while statements (§4.3).
COSC-1336, Lecture 4
70
Summary (cont.)







To write loops using for statements (§4.4).
To discover the similarities and differences of three
types of loop statements (§4.5).
To write nested loops (§4.6).
To learn the techniques for minimizing numerical
errors (§4.7).
To learn loops from a variety of examples (GCD,
FutureTuition, MonteCarloSimulation) (§4.8).
To implement program control with break and continue
(§4.9).
(GUI) To control a loop with a confirmation dialog
(§4.10).
5/9/2017
COSC-1336, Lecture 4
71
Reading suggestions

From [Liang: Introduction to Java programming:
Eight Edition, 2011 Pearson Education,
0132130807]
 Chapter 4 (Loops)
5/9/2017
COSC-1336, Lecture 4
72
Coming up next

From [Liang: Introduction to Java
programming: Eight Edition, 2011 Pearson
Education, 0132130807]

5/9/2017
Chapter 5 (Methods)
COSC-1336, Lecture 4
73
Thank you for your attention!
Questions?
5/9/2017
COSC-1336, Lecture 4
74
Related documents