Iteration 1

advertisement
Iteration
1
Java looping
 Options
 while
 do-while
 for
 Allow programs to control how many times a statement list is
executed
2
Averaging
 Problem
 Extract a list of positive numbers from standard input and
produce their average
 Numbers are one per line
 A negative number acts as a sentinel to indicate that
there are no more numbers to process
 Observations
 Cannot supply sufficient code using just assignments and
conditional constructs to solve the problem
 Don’t how big of a list to process
 Need ability to repeat code as needed
3
Averaging
 Algorithm
 Prepare for processing
 Get first input
 While there is an input to process do {
 Process current input
 Get the next input
 }
 Perform final processing
4
Averaging
 Problem
 Extract a list of positive numbers from standard input and
produce their average
 Numbers are one per line
 A negative number acts as a sentinel to indicate that
there are no more numbers to process
 Sample run
Enter positive numbers one per line.
Indicate end of list with a negative number.
4.5
0.5
1.3
-1
Average 2.1
5
public class NumberAverage {
// main(): application entry point
public static void main(String[] args) {
// set up the input
// prompt user for values
// get first value
// process values one-by-one
while (value >= 0) {
// add value to running total
// processed another value
// prepare next iteration - get next value
}
// display result
if (valuesProcessed > 0)
// compute and display average
else
// indicate no average to display
}
}
int valuesProcessed = 0;
double valueSum = 0;
// set up the input
Scanner stdin = new Scanner (System.in);
// prompt user for values
System.out.println("Enter positive numbers 1 per line.\n"
+ "Indicate end of the list with a negative number.");
// get first value
double value = stdin.nextDouble();
// process values one-by-one
while (value >= 0) {
valueSum += value;
++valuesProcessed;
value = stdin.nextDouble();
}
// display result
if (valuesProcessed > 0) {
double average = valueSum / valuesProcessed;
System.out.println("Average: " + average);
} else {
System.out.println("No list to average");
}
While syntax and semantics
while
(
Expression
)
Action
Logical expression that
determines whether Action
is to be executed
Action is either a single
statement or a statement
list within braces
8
While semantics for averaging problem
Test expression is evaluated at the
start of each iteration of the loop.
// process values one-by-one
while ( value >= 0 ) {
// add value to running total
valueSum += value;
// we processed another value
++valueProcessed;
// prepare to iterate – get the next input
value = stdin.nextDouble();
}
If test expression is true, these statements
are executed. Afterward, the test expression
is reevaluated and the process repeats
9
While Semantics
Expression is
evaluated at the
start of each
iteration of the
loop
Expression
If Expression is
true, Action is
executed
true
Action
false
If Expression is
false, program
execution
continues with
next statement
10
Suppose input contains: 4.5 0.5 1.3 -1
Execution Trace
valuesProcessed
int valuesProcessed = 0;
double valueSum = 0;
0
1
2
3
valueSum
4.5
6.3
5.0
0
value
0.5
1.3
4.5
-1
average
2.1
double value = stdin.nextDouble();
while (value >= 0) {
valueSum += value;
++valuesProcessed;
value = stdin.nextDouble();
}
if (valuesProcessed > 0) {
double average = valueSum / valuesProcessed;
System.out.println("Average: " + average);
}
else {
System.out.println("No list to average");
}
11
Converting text to strictly lowercase
public static void main(String[] args) {
Scanner stdin = new Scanner (System.in);
System.out.println("Enter input to be converted:");
String converted = "";
String currentLine = stdin.nextLine();
while (currentLine != null) {
String currentConversion =
currentLine.toLowerCase();
converted += (currentConversion + "\n");
currentLine = stdin.nextLine();
}
System.out.println("\nConversion is:\n" + converted);
}
12
Sample run
An empty line
was entered
A Ctrl+z was
entered. tI is the
Windows escape
sequence for
indicating
end-of-file
13
Program trace
public static void main(String[] args) {
Scanner stdin = new Scanner (System.in);
System.out.println("Enter input to be converted:");
String converted = "";
String currentLine = stdin.nextLine();
while (currentLine != null) {
String currentConversion =
currentLine.toLowerCase();
converted += (currentConversion + "\n");
currentLine = stdin.nextLine();
}
System.out.println("\nConversion is:\n" + converted);
}
14
Program trace
The append assignment operator updates the representation
of converted to include the current input line
converted += (currentConversion + "\n");
Representation of lower case
conversion of current input line
Newline character is needed
because method nextLine()
"strips" them from the input
15
Converting text to strictly lowercase
public static void main(String[] args) {
Scanner stdin = new Scanner (System.in);
System.out.println("Enter input to be converted:");
String converted = "";
String currentLine = stdin.nextLine();
while (currentLine != null) {
String currentConversion =
currentLine.toLowerCase();
converted += (currentConversion + "\n");
currentLine = stdin.nextLine();
}
System.out.println("\nConversion is:\n" + converted);
}
16
Loop design
 Questions to consider in loop design and analysis
 What initialization
expression?
is
necessary
for
the
loop’s
test
 What initialization is necessary for the loop’s processing?
 What causes the loop to terminate?
 What actions should the loop perform?
 What actions are necessary to prepare for the next
iteration of the loop?
 What conditions are true and what conditions are false
when the loop is terminated?
 When the loop completes what actions are need to
prepare for subsequent program processing?
17
Reading a file
 Background
Same Scanner class!
filename is a String
Scanner fileIn = new Scanner (new File (filename) );
The File class allows access to files
It’s in the java.io package
18
Reading a file
 Class File
 Allows access to files (etc.) on a hard drive
 Constructor File (String s)
 Opens the file with name s so that values can be extracted
 Name can be either an absolute pathname or a pathname
relative to the current working folder
19
Reading a file
Scanner stdin = new Scanner (System.in);
System.out.print("Filename: ");
String filename = stdin.nextLine();
Scanner fileIn = new Scanner (new File (filename));
String currentLine = fileIn.nextLine();
while (currentLine != null) {
System.out.println(currentLine);
currentLine = fileIn.nextLine();
}
Close
Determine
Set
Process
Display
Get
Make
up
first
next
sure
the
standard
file
current
lines
line
line
file
stream
got
fileone
stream
name
aline
input
line
by one
tostream
process
If not, loop is done
20
Quick survey

a)
b)
c)
d)
I feel I understand while loops…
Very well
With some review, I’ll be good
Not really
Not at all
21
Star Wars: Episode III trailer

No, really!
22
The For Statement
The body of the loop iterates
while the test expression is
true
Initialization step
is performed only
After each iteration of the
once -- just prior int currentTerm = 1;
body of the loop, the update
to the first
expression is reevaluated
evaluation of the for ( int i = 0; i < 5; ++i ) {
test expression
System.out.println(currentTerm);
currentTerm *= 2;
The body of the loop displays the
}
current term in the number series.
It then determines what is to be the
new current number in the series
24
Evaluated once
at the beginning
of the for
statements's
execution
If ForExpr is true,
Action is
executed
After the Action
has completed,
the
PostExpression
is evaluated
ForInit
ForExpr
true
Action
PostExpr
After evaluating the
PostExpression, the next
iteration of the loop starts
The ForExpr is
evaluated at the
start of each
iteration of the
loop
false
If ForExpr is
false, program
execution
continues with
next statement
for statement syntax
Logical test expression that determines whether the action and update step are
executed
Initialization step prepares for the
first evaluation of the test
expression
for
( ForInit
; ForExpression
Update step is performed after
the execution of the loop body
; ForUpdate
) Action
The body of the loop iterates whenever
the test expression evaluates to true
26
for vs. while
 A for statement is almost like a while statement
for ( ForInit; ForExpression; ForUpdate ) Action
is ALMOST the same as:
ForInit;
while ( ForExpression ) {
Action;
ForUpdate;
}
 This is not an absolute equivalence!
 We’ll see when they are different below
27
Variable declaration
 You can declare a variable in any block:
while ( true ) {
int n = 0;
n++;
System.out.println (n);
}
System.out.println (n);
Variable n gets created
(and initialized) each time
Thus, println() always
prints out 1
Variable n is not
defined once while
loop ends
As n is not defined
here, this causes
an error
28
Variable declaration
 You can declare a variable in any block:
if ( true ) {
int n = 0;
n++;
System.out.println (n);
}
System.out.println (n);
Only difference
from last slide
29
Execution Trace
i
for ( int i = 0; i < 3; ++i ) {
0
3
2
1
System.out.println("i is " + i);
}
System.out.println("all done");
i is 0
i is 1
i is 2
all done
Variable i has gone
out of scope – it
is local to the loop
30
for vs. while

An example when a for loop can be directly translated into a while
loop:
int count;
for ( count = 0; count < 10; count++ ) {
System.out.println (count);
}

Translates to:
int count;
count = 0;
while (count < 10) {
System.out.println (count);
count++;
}
31
for vs. while
 An example when a for loop CANNOT be directly translated
into a while loop:
only difference
for ( int count = 0; count < 10; count++ ) {
System.out.println (count);
}
count is NOT defined here
 Would (mostly) translate as:
int count = 0;
while (count < 10) {
System.out.println (count);
count++;
}
count IS defined here
32
for loop indexing
 Java (and C and C++) indexes everything from zero
 Thus, a for loop like this:
for ( int i = 0; i < 10; i++ ) { ... }
 Will perform the action with i being value 0 through 9, but
not 10
 To do a for loop from 1 to 10, it would look like this:
for ( int i = 1; i <= 10; i++ ) { ... }
33
Quick survey

a)
b)
c)
d)
I feel I understand for loops…
Very well
With some review, I’ll be good
Not really
Not at all
34
Fractals
35
Nested loops
int m = 2;
int n = 3;
for (int i = 0; i < n; ++i) {
System.out.println("i is " + i);
for (int j = 0; j < m; ++j) {
System.out.println("
j is " + j);
}
i is 0
}
j is 0
j is 1
i is 1
j is 0
j is 1
i is 2
j is 0
j is 1
37
Nested loops
int m = 2;
int n = 4;
for (int i = 0; i < n; ++i) {
System.out.println("i is " + i);
for (int j = 0; j < i; ++j) {
System.out.println("
j is " + j);
}
}
i is 0
i is 1
j is
i is 2
j is
j is
i is 3
j is
j is
j is
38
0
0
1
0
1
2
do-while loops
 We are going to skip these
 Thus, they won’t be on the exams
 You can look at them in the slides and/or the book
39
A digression: Perl again

Consider the statement:
if ( !flag ) {
...
} else {
...
}

Perl has a command unless:
unless ( flag ) {
...
} else {
...
}

An unless command is a if statement with a negated condition

It can get a bit confusing, though
 The else of an unless…
44
A digression: Perl again

Consider the statement:
while ( !flag ) {
...
}

Perl has a command until:
until ( flag ) {
...
}

An until command is a while loop with a negated condition

As most people are quite used to if-else and while, unless and until
are rarely used
45
The continue keyword

The continue keyword will immediately start the next iteration of the
loop
 The rest of the current loop is not executed
for ( int a = 0; a <= 10; a++ ) {
if ( a % 2 == 0 ) {
continue;
}
System.out.println (a + " is odd");
}

Output:
1
3
5
7
9
is
is
is
is
is
odd
odd
odd
odd
odd
46
The break keyword

The break keyword will immediately stop the execution of the loop
 Execution resumes after the end of the loop
for ( int a = 0; a <= 10; a++ ) {
if ( a == 5 ) {
break;
}
System.out.println (a + " is less than five");
}

Output:
0
1
2
3
4
is
is
is
is
is
less
less
less
less
less
than
than
than
than
than
five
five
five
five
five
47
Quick survey

a)
b)
c)
d)
I feel I understand loops, break, continue, etc…
Very well
With some review, I’ll be good
Not really
Not at all
48
Human stupidity
49
Four Hobos
 An example of a program that uses nested for loops
 Credited to Will Shortz, crossword puzzle editor of the New
York Times
 And NPR’s Sunday Morning Edition puzzle person
 This problem is in section 6.10 of the text
50
Problem
 Four hobos want to split up 200 hours of work
 The smart hobo suggests that they draw straws with numbers
on it
 If a straw has the number 3, then they work for 3 hours on 3
days (a total of 9 hours)
 The smart hobo manages to draw the shortest straw
 How many ways are there to split up such work?
 Which one did the smart hobo choose?
51
Analysis
 We are looking for integer solutions to the formula:
a2+b2+c2+d2 = 200
 Where a is the number of hours & days the first hobo
worked, b for the second hobo, etc.
 We know the following:
 Each number must be at least 1
 No number can be greater than 200 = 14
 That order doesn’t matter
 The combination (1,2,1,2) is the same as (2,1,2,1)
 Both combinations have two short and two long
straws
 We will implement this with nested for loops
52
Implementation
public class FourHobos {
public static void main (String[] args) {
for ( int a = 1; a <= 14; a++ ) {
for ( int b = 1; b <= 14; b++ ) {
for ( int c = 1; c <= 14; c++ ) {
for ( int d = 1; d <= 14; d++ ) {
if ( (a <= b) && (b <= c) && (c <= d) ) {
if ( a*a+b*b+c*c+d*d == 200 ) {
System.out.println ("(" + a + ", " + b
+ ", " + c + ", " + d + ")");
}
}
}
}
}
}
}
}
53
Results
 The output:
(2, 4, 6, 12)
(6, 6, 8, 8)
 Not surprisingly, the smart hobo picks the short straw of the
first combination
54
Alternate implementation
 We are going to rewrite the old code in the inner most for
loop:
if ( (a <= b) && (b <= c) && (c <= d) ) {
if ( a*a+b*b+c*c+d*d == 200 ) {
System.out.println ("(" + a + ", " + b
+ ", " + c + ", " + d + ")");
}
}
 First, consider the negation of
( (a <= b) && (b <= c) && (c <= d) )
 It’s ( !(a <= b) || !(b <= c) || !(c <= d) )
 Or ( (a > b) || (b > c) || (c > d) )
55
Alternate implementation
 This is the new code for the inner-most for loop:
if ( (a > b) || (b > c)
continue;
}
if ( a*a+b*b+c*c+d*d !=
continue;
}
System.out.println ("("
+ c
|| (c > d) ) {
200 ) {
+ a + ", " + b + ", "
+ ", " + d + ")");
56
Revised implementation
public class FourHobos {
public static void main (String[] args) {
for ( int a = 1; a <= 14; a++ ) {
for ( int b = 1; b <= 14; b++ ) {
for ( int c = 1; c <= 14; c++ ) {
for ( int d = 1; d <= 14; d++ ) {
if ( (a > b) || (b > c) || (c > d) ) {
continue;
}
if ( a*a+b*b+c*c+d*d != 200 ) {
continue;
}
System.out.println ("(" + a + ", " + b + ", "
+ c + ", " + d + ")");
}
}
}
}
57
}
}
Quick survey

a)
b)
c)
d)
I feel I understand that example…
Very well
With some review, I’ll be good
Not really
Not at all
58
Today’s demotivators
59
Data set manipulation
 Another example to develop code for
 Develops a class
 Uses loops and if-elses
 Booyea!
60
Data set manipulation
 Often five values of particular interest
 Minimum
 Maximum
 Mean (average)
 Standard deviation
 Size of data set
 Let’s design a data set representation
 The data set represents a series of numbers
 Note that the numbers themselves are not remembered
by the DataSet
 Only properties of the set (average, minimum, etc.)
 We’re going to ignore the standard deviation
61
Data set properties (instance variables)
 private int n
 Number of values in the data set being represented
 private double minimumValue
 Minimum value in the data set being represented
 private double maximumValue
 Maximum value in the data set being represented
 private double xSum
 The sum of values in the data set being represented
62
Constructors
 public DataSet()
 Initializes a representation of an empty data set
 public DataSet(String s)
 Initializes the data set using the values from the file with
name s
 public DataSet(File filep)
 Initializes the data set using the values from the file
represented by filep
 We aren’t going to develop that here…
64
Methods
 public double getMinimum()
 Returns the minimum value in the data set
 If the data set is empty, then Double.NaN is returned
 Double.NaN is the Java double value representing the
status not-a-number
 public double getMaximum()
 Returns the maximum value in the data set
 If the data set is empty, then Double.NaN is returned
65
More methods
 public double getAverage()
 Returns the average value in the data set
 If the data set is empty, then Double.NaN is returned
 public int getSize()
 Returns the number of values in the data set being
represented
66
More more methods
 public void addValue(double x)
 Adds the value x to the data set being represented
 public void clear()
 Sets the representation to that of an empty data set
 public void load(String s)
 Adds the vales from the file with name s to the data set
being represented
 public void load(File filep)
 Adds the vales from the file represented by filep to the
data set being represented
67
 Left to interested student
Example usage
DataSet dataset = new DataSet("age.txt");
System.out.println();
System.out.println("Minimum: " + dataset.getMinimum());
System.out.println("Maximum: " + dataset.getMaximum());
System.out.println("Mean: " + dataset.getAverage());
System.out.println("Size: " + dataset.getSize());
System.out.println();
dataset.clear();
dataset.load("stature.txt");
System.out.println("Minimum: " + dataset.getMinimum());
System.out.println("Maximum: " + dataset.getMaximum());
System.out.println("Mean: " + dataset.getAverage());
System.out.println("Size: " + dataset.getSize());
System.out.println();
68
dataset.clear();
Example usage
dataset.load("foot-length.txt");
System.out.println("Minimum: " + dataset.getMinimum());
System.out.println("Maximum: " + dataset.getMaximum());
System.out.println("Mean: " + dataset.getAverage());
System.out.println("Size: " + dataset.getSize());
System.out.println();
dataset.clear();
System.out.println("Minimum: " + dataset.getMinimum());
System.out.println("Maximum: " + dataset.getMaximum());
System.out.println("Mean: " + dataset.getAverage());
System.out.println("Size: " + dataset.getSize());
System.out.println();
69
Example usage
70
Methods getMinimum() and getMaximum()
 Straightforward implementations given correct setting of
instance variables
public double getMinimum() {
return minimumValue;
}
public double getMaximum() {
return maximumValue;
}
71
Method getSize()
 Straightforward implementations given correct setting of
instance variables
public int getSize() {
return n;
}
72
Method getAverage()
 Need to take into account that data set might be empty
public double getAverage() {
if (n == 0) {
return Double.NaN;
}
else {
return xSum / n;
}
}
73
DataSet constructors
 Straightforward using clear() and load()
public DataSet() {
clear();
}
public DataSet(String s) {
load(s);
}
74
Facilitator clear()
public void clear() {
n = 0;
xSum = 0;
minimumValue = Double.NaN;
maximumValue = Double.NaN;
}
75
Facilitator addValue()
public void addValue(double x) {
xSum += x;
++n;
if (n == 1) {
minimumValue = x;
maximumValue = x;
}
else if (x < minimumValue) {
minimumValue = x;
}
else if (x > maximumValue) {
maximumValue = x;
}
}
76
Facilitator load()
public void load(String s) {
// get a reader for the file
Scanner fileIn = new Scanner (new File(s));
// add values one by one
String currentLine = fileIn.nextLine();
while (currentLine != null) {
double x = Double.parseDouble(currentLine);
addValue(x);
currentLine = fileIn.nextLine();
}
// close up file
}
77
Quick survey

a)
b)
c)
d)
I felt I understood the material in this slide set…
Very well
With some review, I’ll be good
Not really
Not at all
78
Quick survey

a)
b)
c)
d)
The pace of the lecture for this slide set was…
Fast
About right
A little slow
Too slow
79
Quick survey

a)
b)
c)
d)
How interesting was the material in this slide
set? Be honest!
Wow! That was SOOOOOOO cool!
Somewhat interesting
Rather boring
Zzzzzzzzzzz
80
Sand Castles
81
Survey time!
82
Download