Top Banner
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
99

Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Dec 13, 2015

Download

Documents

Naomi Underwood
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Iteration

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Page 2: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Java looping• Options

– while– do-while– for

• Allow programs to control how many times a statement list is executed

Page 3: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

Page 4: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

• 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

Page 5: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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 runEnter positive numbers one per line.Indicate end of list with a negative number.4.50.51.3-1Average 2.1

Page 6: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

public class NumberAverage {// main(): application entry pointpublic static void main(String[] args)

throws IOException {// set up the list processing

// prompt user for values

// get first value

// process values one-by-onewhile (value >= 0) {

// add value to running total// processed another value// prepare next iteration - get next value

}

// display resultif (valuesProcessed > 0)

// compute and display averageelse

// indicate no average to display}

}

Page 7: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

System.out.println("Enter positive numbers 1 per line.\n" + "Indicate end of the list with a negative number.");

Scanner stdin = new Scanner(System.in);

int valuesProcessed = 0;double valueSum = 0;

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");}

Page 8: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

While syntax and semantics

Logical expression thatdetermines whether Action

is to be executed — ifExpression evaluates to

true, then Action isexecuted; otherwise, the

loop is terminated

while ( Expression ) Action

Action is either a singlestatement or a statementlist within braces. The actionis also known as the body ofthe loop. After the body is

executed, the test expressionis reevaluated. If the

expression evaluates to true,the body is executed again.

The process repeats until thetest expression evaluates to

false

Page 9: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

While semantics for averaging problem

// process values one-by-onewhile (value >= 0) { // add value to running total valueSum += value; // processed another value ++valuesProcessed; // prepare to iterate -- get the next input value = stdin.nextDouble());}

Test expression is evaluated at thestart of each iteration of the loop.Its value indicates whether there is anumber to process

If test expression is true, these statementsare executed. Afterward, the test expression

is reevaluated and the process repeats

Page 10: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

While Semantics

Expr essi on

Act i on

true false

Expression isevaluated at the

start of eachiteration of the

loop

If Expression istrue, Action is

executed If Expression isfalse, program

executioncontinues withnext statement

Page 11: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

Suppose input contains: 4.5 0.5 1.3 -1

Page 12: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

Suppose input contains: 4.5 0.5 1.3 -1

0valuesProcessed

Page 13: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

Suppose input contains: 4.5 0.5 1.3 -1

0valuesProcessed

0

Page 14: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

0valuesProcessed

0

4.5

Page 15: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

0valuesProcessed

0

4.5

Page 16: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

0valuesProcessed

0

4.5

4.5

Page 17: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

0valuesProcessed

4.5

4.5

1

Page 18: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

1valuesProcessed

4.5

4.50.5

Page 19: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

1valuesProcessed

4.5

0.5

Page 20: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

1valuesProcessed

4.5

0.5

5.0

Page 21: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

1valuesProcessed

5.0

0.5

2

Page 22: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

2valuesProcessed

5.0

0.51.3

Page 23: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

2valuesProcessed

5.0

1.3

Page 24: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

2valuesProcessed

5.0

1.3

6.3

Page 25: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

2valuesProcessed

6.3

1.3

3

Page 26: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

3valuesProcessed

6.3

1.3-1

Page 27: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

3valuesProcessed

6.3

-1

Page 28: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

3valuesProcessed

6.3

-1

Page 29: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

3valuesProcessed

6.3

-1

average 2.1

Page 30: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Traceint valuesProcessed = 0;double valueSum = 0;

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");}

valueSum

value

Suppose input contains: 4.5 0.5 1.3 -1

3valuesProcessed

6.3

-1

average 2.1

Page 31: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Converting text to strictly lowercasepublic static void main(String[] args) {

Scanner stdin = new Scanner(System.in);

System.out.println("Enter input to be converted:");

String converted = "";

while (stdin.hasNext()) {String currentLine = stdin.nextLine();String currentConversion =

currentLine.toLowerCase();converted += (currentConversion + "\n");

}

System.out.println("\nConversion is:\n" + converted);}

Page 32: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Sample run

A Ctrl+z wasentered. It is theWindows escape

sequence forindicatingend-of-file

An empty linewas entered

Page 33: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Program tracepublic static void main(String[] args) {

Scanner stdin = new Scanner(System.in);

System.out.println("Enter input to be converted:");

String converted = "";

while (stdin.hasNext()) {String currentLine = stdin.nextLine();String currentConversion =

currentLine.toLowerCase();converted += (currentConversion + "\n");

}

System.out.println("\nConversion is:\n" + converted);}

Page 34: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Program tracepublic static void main(String[] args) {

Scanner stdin = new Scanner(System.in);

System.out.println("Enter input to be converted:");

String converted = "";

while (stdin.hasNext()) {String currentLine = stdin.nextLine();String currentConversion =

currentLine.toLowerCase();converted += (currentConversion + "\n");

}

System.out.println("\nConversion is:\n" + converted);}

Page 35: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Program tracepublic static void main(String[] args) {

Scanner stdin = new Scanner(System.in);

System.out.println("Enter input to be converted:");

String converted = "";

while (stdin.hasNext()) {String currentLine = stdin.nextLine();String currentConversion =

currentLine.toLowerCase();converted += (currentConversion + "\n");

}

System.out.println("\nConversion is:\n" + converted);}

Page 36: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Program tracepublic static void main(String[] args) {

Scanner stdin = new Scanner(System.in);

System.out.println("Enter input to be converted:");

String converted = "";

while (stdin.hasNext()) {String currentLine = stdin.nextLine();String currentConversion =

currentLine.toLowerCase();converted += (currentConversion + "\n");

}

System.out.println("\nConversion is:\n" + converted);}

Page 37: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Program trace

Representation of lower caseconversion of current input

line

converted += (currentConversion + "\n");

The append assignment operator updates therepresentation of converted to include the current input line

Newline character is neededbecause method readLine()"strips" them from the input

Page 38: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Converting text to strictly lowercasepublic static void main(String[] args) {

Scanner stdin = new Scanner(System.in);

System.out.println("Enter input to be converted:");

String converted = "";

while (stdin.hasNext()) {String currentLine = stdin.nextLine();String currentConversion =

currentLine.toLowerCase();converted += (currentConversion + "\n");

}

System.out.println("\nConversion is:\n" + converted);}

Page 39: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Loop design• Questions to consider in loop design and analysis

– What initialization is necessary for the loop’s test expression?

– 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?

Page 40: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a file• Background

Scanner provids a way toprocess text input

Scanner stdin = new Scaner(System.in));

System.in is an InputStreamvariable. The stream contains text

Page 41: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a file• Class File

– Provides a system-independent way of representing a file name

• Constructor File(String s)– Creates a File with name s– Name can be either an absolute pathname or a pathname

relative to the current working folder

Page 42: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Page 43: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Set up standard input stream

Page 44: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Determine file name

Page 45: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Determine the associated file

Page 46: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Set up file stream

Page 47: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Process lines one by one

Page 48: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Is there any text

Page 49: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Get the next line of text

Page 50: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Display current line

Page 51: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Make sure there is another to processIf not, loop is done

Page 52: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Reading a fileScanner stdin = new Scanner(System.in);

System.out.print("Filename: ");String filename = stdin.next();

File file = new File(filename);

Scanner fileIn = new Scanner(file);

while (fileIn.hasNext()) {String currentLine = fileIn.nextLine();System.out.println(currentLine);

}

fileIn.close();

Close the stream

Page 53: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The For Statement

int currentTerm = 1;

for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;

}

Page 54: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The For Statement

int currentTerm = 1;

for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;

}

Initialization stepis performed onlyonce -- just prior

to the firstevaluation of thetest expression

Page 55: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The For Statement

int currentTerm = 1;

for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;

}

The body of the loop iterateswhile the test expression istrueInitialization step

is performed onlyonce -- just prior

to the firstevaluation of thetest expression

Page 56: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The For Statement

int currentTerm = 1;

for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;

}

The body of the loop iterateswhile the test expression istrueInitialization step

is performed onlyonce -- just prior

to the firstevaluation of thetest expression

The body of the loop displays thecurrent term in the number series.It then determines what is to be thenew current number in the series

Page 57: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The For Statement

int currentTerm = 1;

for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;

}

After each iteration of thebody of the loop, the updateexpression is reevaluated

The body of the loop iterateswhile the test expression istrueInitialization step

is performed onlyonce -- just prior

to the firstevaluation of thetest expression

The body of the loop displays thecurrent term in the number series.It then determines what is to be thenew current number in the series

Page 58: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

For Expr

Act i on

true false

For I ni t

Post Expr

Evaluated onceat the beginning

of the forstatements's

executionThe ForExpr is

evaluated at thestart of each

iteration of theloop

If ForExpr is true,Action isexecuted

After the Actionhas completed,

thePostExpression

is evaluated

If ForExpr isfalse, program

executioncontinues withnext statement

After evaluating thePostExpression, the next

iteration of the loop starts

Page 59: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

For statement syntax

Logical test expression that determines whether the action and update step areexecuted

for ( ForInit ; ForExpression ; ForUpdate ) Action

Update step is performed afterthe execution of the loop body

Initialization step prepares for thefirst evaluation of the test

expression

The body of the loop iterates wheneverthe test expression evaluates to true

Page 60: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i 0

Page 61: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i 0

Page 62: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0

i 0

Page 63: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println(“i is " + i);}

System.out.println(“all done");

i is 0

i 0

Page 64: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0

i 1

Page 65: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0

i 1

Page 66: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1

i 1

Page 67: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1

i 1

Page 68: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1

i 2

Page 69: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1

i 2

Page 70: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1i is 2

i 2

Page 71: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1i is 2

i 2

Page 72: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1i is 2

i 3

Page 73: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1i is 2

i 3

Page 74: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Execution Tracefor (int i = 0; i < 3; ++i) {

System.out.println("i is " + i);}

System.out.println("all done");

i is 0i is 1i is 2all done

3

Variable i has gone out of scope – it

is local to the loop

Page 75: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Nested loopsint 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);}

}

Page 76: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Nested loopsint 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 1i is 1 j is 0 j is 1i is 2 j is 0 j is 1

Page 77: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The do-while statement• Syntax

do Action while (Expression)

• Semantics– Execute Action– If Expression is true then

execute Action again– Repeat this process until Expression evaluates to false

• Action is either a single statement or a group of statements within braces

Action

true

false

Expression

Page 78: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Picking off digits• Consider

System.out.print("Enter a positive number: ");int number = stdin.nextInt());do { int digit = number % 10; System.out.println(digit); number = number / 10;} while (number != 0);

• Sample behaviorEnter a positive number: 11299211

Page 79: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Problem solving

Page 80: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Internet per 100 people for 189 entities

0.09 0.16 8.97 0.23 6.52 6.75 1.42 13.65 34.45

0.16 4.32 5.84 0.08 3.74 1.78 22.89 6.24 0.25

1.44 1.01 1.54 2.94 9.14 5.28 0.08 0.07 0.05

41.3 1.84 0.04 0.04 16.58 1.74 38.64 13.7 2.07

5.67 0.27 5.59 0.54 17.88 9.71 0.01 36.59 0.22

1.86 1.42 0.71 0.8 0.15 0.13 27.21 73.4 1.47

14.43 6.43 1.22 0.92 0.42 29.18 0.15 9.47 4.36

0.7 0.1 0.25 6.04 0.25 0.62 7.15 59.79 0.54

0.39 20.7 20.26 23.04 3.11 29.31 2.53 0.62 0.65

40.25 7.84 1.06 0.11 6.19 8.58 0.19 0.02 0.18

22.66 0.19 0.15 15.9 2.23 0.17 13.08 1.17 0.19

2.74 39.71 1.26 0.71 0.06 0.01 1.71 0.22 24.39

21.67 0.99 0.04 0.18 49.05 25.05 3.55 0.09 1.1

2.81 0.73 9.74 2.01 7.25 24.94 10.22 5.01 1.2

3.57 0.06 4.79 3.09 0.56 48.7 4.36 0.93 0.42

0.1 29.87 12.03 15.08 0.46 0.01 5.49 13.43 0.64

2.7 0.99 45.58 29.62 0.19 28.1 0.05 3.79 2.47

7.73 2.61 3.06 0.13 0.18 0.69 28.2 30.12 0.33

11.09 0.49 2.03 3.93 0.25 0.08 3.76 0.19 0.37

25.86 0.22 0.27 7.78 37.23 1.75 0.94 1.8 6.09

3.17 18.6 7.4 0.1 0.86 45.07 11.15 7.29

Page 81: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Data set manipulation• Often five values of particular interest

– Minimum– Maximum– Mean– Standard deviation– Size of data set

• Let’s design a data set representation

Page 82: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

What facilitators are needed?

Page 83: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Implication on facilitators • public double getMinimum()

– Returns the minimum value in the data set. If the data set is empty, then Double.NaN is returned, where 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

Page 84: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Implication on facilitators • public double getAverage()

– Returns the average value in the data set. If the data set is empty, then Double.NaN is returned

• public double getStandardDeviation()– Returns the standard deviation value of the data set. If the

data set is empty, then Double.NaN is returned

• Left to the interested student

• public int getSize()– Returns the number of values in the data set being

represented

Page 85: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

What constructors are needed?

Page 86: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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 file)– Initializes the data set using the values from the file

• Left to interested student

Page 87: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Other 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 file)– Adds the vales from the file to the data set being represented

• Left to interested student

Page 88: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

What instance variables are needed?

Page 89: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

Page 90: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Example usageDataSet 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();dataset.clear();

Page 91: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Example usagedataset.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();

Page 92: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Example usage

Page 93: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Methods getMinimum() and getMaximum()

• Straightforward implementations given correct setting of instance variables

public double getMinimum() {return minimumValue;

}

public double getMaximum() {return maximumValue;

}

Page 94: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Method getSize()

• Straightforward implementations given correct setting of instance variables

public int getSize() {return n;

}

Page 95: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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;}

}

Page 96: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

DataSet constructors

• Straightforward using clear() and load()

public DataSet() {clear();

}

public DataSet(String s) throws IOException { clear();

load(s);}

Page 97: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Facilitator clear()

public void clear() {n = 0;xSum = 0;minimumValue = Double.NaN;maximumValue = Double.NaN;

}

Page 98: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Facilitator add()

public void addValue(double x) {xSum += x;++n;if (n == 1) {

minimumValue = maximumValue = x;}else if (x < minimumValue) {

minimumValue = x;}else if (x > maximumValue) {

maximumValue = x;}

}

Page 99: Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Facilitator load()public void load(String s) throws IOException {

// get a reader for the file Scanner fileIn = new Scanner( new File(s) );

// add values one by one while (fileIn.hasNext()) {

double x = fileIn.nextDouble);addValue(x);

}

// close up filefileIn.close();

}