Top Banner
Chapter 6 Loops and Files
50

Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

Dec 20, 2015

Download

Documents

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: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

Chapter 6

Loops and Files

Page 2: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

2

Knowledge Goals

• Understand the semantics of while loop• Understand when a count-controlled loop is

appropriate• Understand when an event-controlled loop is

appropriate• Know the difference between an iteration

counter and an event counter• Know where nested loops are needed in a

problem solution

Page 3: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

3

Knowledge Goals

• Understand the principles of testing programs that contain loops

• Recognize when file input/output is appropriate and how it differs from interactive input/output

Page 4: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

4

Skill Goals

• Construct syntactically correct while loops• Construct count-controlled loops with a while

statement• Construct event-controlled loops with a while

statement• Use the end-of-file condition to control the

input of data• Use flags to control the execution of a while

statement

Page 5: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

5

Skill Goals

• Construct counting loops with a while statement

• Construct summing loops with a while statement

• Write statements to read from a text file• Write statements to write to a text file• Write applications that use data files for input

and output

Page 6: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

6

Looping Control Flow

Aroundand

aroundand…

Page 7: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

7

Looping Control Flow

Loop

A control structure that causes a statement or group of statements to be executed repeatedly

Count-controlled loop

A loop that executes a specified number of times

Event-controlled loop

A loop that terminates when something happens inside the loop body to signal that the loop should be exited

Page 8: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

8

Looping Control Flow

Page 9: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

9

Looping Control Flow

Seethe

difference?

Page 10: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

10

Looping Control FlowLoop entry

The point at which the flow of control reaches the first statement inside the loop

Iteration

An individual repetition of the body of the loop

Loop test

The point at which the while expression is evaluated and the decision is made to either repeat or exit

Loop exit

The point at which the repetition ends

Termination condition

The condition that causes the loop to be exited

Page 11: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

11

Looping Control Flowloop entry

each time executedis an iteration

loop test

exited the loop Expression is false

Phases of loop execution

Page 12: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

12

Looping Control Flow

Count-controlled loops– A variable keeps track of the number of

times the loop is executed– The variable must be initialized outside the

loop– It must be tested at the beginning of the loop– It must be incremented within the loop– It is a counter (a variable that is incremented

repeatedly)

Page 13: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

13

Looping Control Flow

int loopCount; // Declare loop variable

loopCount = 1; // Initialize loop variable

while (loopCount <= 10) // Test expression

{

. // Repeated actions

.

.

loopCount++; // Update loop variable

}

How many times does this loop execute?

Page 14: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

14

Looping Control Flow

int count; // Declare loop variable

count = 0; // Initialize loop variable

while (count <= 4) // Test expression

{ // Repeated action

System.out.println(“count is “ + count); count ++; // Update loop variable

}

System.out.println(“Done”);

How many times does this loop execute?

Page 15: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

15

Looping Control Flow

Event-controlled loops– An event within the loop controls the

repetition– The event must be initialized outside the

loop– The event must be tested at the beginning

of the loop– The event must be re-evaluated within the

loop

Page 16: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

16

Looping Control Flow

Eevent: guess is good enough

Initialize: set goodEnough to false

Test: while (!goodEnough)

Re-evaluate set goodEnough to (square - guess*guess) < some threshold

Calculatingsquare

root

Page 17: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

17

Looping Control Flowpublic class NewMath{ static double squareRoot(double square) { double guess = square/4.0; boolean goodEnough = false; while (!goodEnough) { guess = ((square / guess) + guess)/2.0; goodEnough = Math.abs(square - guess*guess) < 0.001; } return guess; }}

Page 18: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

18

File Input/Output

Devices used for file storage

Page 19: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

19

File Input/Output

Page 20: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

20

File Input/Output

Character stream file

A file that is stored as a sequence of characters

Java provides classes that allow us to read from a file just as we read from the keyboard and write to a file just as we wrote to the screen

import java.io.*;

What are the advantages of using files?

Page 21: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

21

File Input/Output

To use a file, we must– Import package java.io.*– Choose valid identifiers and types for the file

variables and declare them– Instantiate a file object for each file variable– Use the file identifiers in I/O statements

(using available methods such as nextLine, nextInt, print, println)

– Close the files when through

Page 22: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

File Input/Output

What does instantiating a file do? – Associates the Java identifier for your file

with the physical (disk) name for the file– Places a file pointer at the very beginning of

the file, pointing to the first character in it– If the output file does not exist on disk, an

empty file with that name is created– If the output file already exists, it is erased

Page 23: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

File Input/Output

your variable

(of type Scanner)

your variable

(of type PrintWriter)

disk file“myInfile”

disk file“myOutfile”

executingprogram

input data output data

import.java.io.*;

Page 24: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

24

File Input/Output

Scanner in = new Scanner(System.in);

FileReader inReader = new FileReader("myInfile");

Scanner inFile = new Scanner(inReader);

Sets up for keyboard

Set up to read "myInfile" All the Scanner methods can be applied to inFile

Page 25: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

25

File Input/Output

Recall that– An exception is an unusual situation

detected while a program is running– Java recognizes two types of exceptions,

checked and unchecked – Unchecked exceptions can be ignored, but

checked exceptions must be explicitly recognized by the program

Page 26: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

26

File Input/Output

Scanner inFile =

new Scanner(new FileReader("inData"));

If file "inData" cannot be found on the disk, an IOException is thrown, and IOExceptions are checked exceptionspublic static void main(String args[]) throws IOException

Passes the exception

to the next le

vel

See Chapter 7 for how to handle it ourselves

Page 27: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

27

File Input/OutputWhat about file output?Remember our old friends print() and println()?

PrintWriter outFile = new PrintWriter (new FileWriter("outFile.dat"));outFile.println("Hello world!");

writes the string argument on file outFile, which can be found on the disk under "outFile.dat"

println() and print() behave the same for a file as they do for System.out

Page 28: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

28

File Input/Output

See thedifferencebetween

constructorsfor input

andoutputfiles

?

Page 29: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

29

Loops and Files

Count-controlled loop Read exactly 100 blood pressures from a file

End-of-file controlledloop

Read all the blood pressures from a file no matter how many are there

Flag-controlled loop

Read blood pressures until a dangerously high BP (200 or more) is read

Sentinel-controlled loop

Read blood pressures until a negative value is found

Page 30: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

30

public class ReadFile{ public static void main(String args[]) throws IOException { int count = 0; Scanner in = new Scanner(new FileReader("BP")); int thisBP; System.out.println("Blood pressures on file BP: "); // Assumption: There are at least 100 values while (count <= 100) { thisBP = in.nextInt(); System.out.print(thisBP + " "); count++; } System.out.println(); in.close(); }}

Count-Controlled loop

Page 31: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

31

public class ReadFile{ public static void main(String args[]) throws IOException { Scanner in = new Scanner(new FileReader("BP")); int thisBP; System.out.println("Blood pressures on file BP: "); while (in.hasNextInt()) { thisBP = in.nextInt(); System.out.print(thisBP + " "); } System.out.println(); in.close(); }}

End-of-file controlled loop

Page 32: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

32

Loops and Files

Use hasNextInt… rather than

hasNextLine for loop test

in.nextInt(); 42<EOLN>

in.hasNextInt(); <EOF> (returns false)

in.nextInt(); 42<EOLN>

in.hasNextLine(); <EOF> (returns true)

Page 33: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

33

public class ReadFile{ public static void main(String args[]) throws IOException { Scanner in = new Scanner(new FileReader("BP")); int thisBP; boolean flag = in.hasNextInt(); System.out.println("Blood pressures on file BP: "); while (flag) { thisBP = in.nextInt(); flag = thisBP < 200 && in.hasNextInt(); if (flag) System.out.print(thisBP + " "); } System.out.println(); in.close(); }}

Flag-controlled loop

Page 34: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

34

Loops and Files

Sentinel-Controlled Loops

Sentinel

A special data value that is used to indicate the end of the data; requires a “priming read”

– read one data value (or set of data values) before entering the while loop

– process data value(s) and then read next value(s) at end of loop

Page 35: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

35

public class ReadFile{ public static void main(String args[]) throws IOException { Scanner in = new Scanner(new FileReader("BP")); int thisBP = in.nextInt(); System.out.println("Blood pressures on file BP: "); while (thisBP > 0) { System.out.print(thisBP + " "); thisBP = in.nextInt(); } System.out.println(); in.close(); }}

Sentinel-controlled loop

Page 36: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

36

Loops and Files

Page 37: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

37

Loops and Files

Common processes within a loopCounting

– End-of-file loop that counts the number of values– Sentinel-controlled loop that counts the number of

values– Any loop that reads and counts the number of positive

values– Any loop that reads and counts the number of values

over a certain threshold

Summing– Any loop that reads and sums all data values– Any loop that reads and sums certain values

Page 38: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

38

Loops and Files

Iteration counter

A counter variable that is incremented in each iteration of a loop

Event counter

A variable that is incremented each time a particular event occurs

Are loop control variables always iteration counters?

Page 39: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

39

How to Design Loops

Seven points to consider when designing loops

1. What condition ends the loop?

2. How should the condition be initialized?

3. How should the condition be updated?

4. What is the process being repeated?

5. How should the process be initialized?

6. How should the process be updated?

7. What is the state of the code on exiting the loop?

Page 40: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

40

How to Design Loops

Key Phrase Termination conditionHow many values in file? ?

How many upper case letters? ?

Are there any negative values? ?

How many negative values

and how many positive values? ?

What is the sum of the positive values? ?

Are all the values less than 300? ?

What is the largest value before a

negative value is encountered? ?

Page 41: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

41

How to Design Loops

What is the process within Loop?How many values in file? ?

How many upper case letters? ?

Are there any negative values? ?

How many negative values

and how many positive values? ?

What is the sum of the positive values? ?

Are all the values less than 300? ?

What is the largest value before a

negative value is encountered? ?

Page 42: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

42

How to Design Loops

What is the state on exit?How many values in file? ?

How many upper case letters? ?

Are there any negative values? ?

How many negative values

and how many positive values? ?

What is the sum of the positive values? ?

Are all the values less than 300? ?

What is the largest value before a

negative value is encountered? ?

Page 43: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

43

Nested Loops

Page 44: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

44

Nested Loop

Algorithm for designing nested loops

Design outer loop– process is task name for inner loop

Design inner loop

It can't be that easy!

Page 45: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

45

Nested Loops

Print number of uppercase characters in each line of a file

Termination condition: EOF is true

Process: Count uppercase characters

State at end:

file has been read

line contains the last line read

count contains the number of uppercase

values in the last line

Page 46: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

46

Nested LoopsOpen file for reading

while NOT EOF

Read line

CountUpperCase

CountUpperCase

Set count to 0

Set index to 0

while index < line.length()

letter = line.charAt();

if isUpperCase(letter)

Increment count

increment index

isUpperCaseis inclass

Character

Page 47: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

47

public static void main (String[] args) throws IOException { String line; int count; int index; char letter; Scanner inFile = new Scanner(new FileReader("text")); while (inFile.hasNextLine()) { line = inFile.nextLine(); count = 0; index = 0; while (index < line.length()) {

letter = line.charAt(index); if (Character.isUpperCase(letter)) count++; index++;

} System.out.println("Uppercase characters: "+ count); } inFile.close(); }

Page 48: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

48

Testing Loops

Should test a loop for four special cases:

1. Loop is skipped entirely

2. Loop body executes just one

3. Loop executes some normal number of times

4. Loop fails to exit

CountUCL was tested with 3. Can you design cases for 1, 2, and 4?

Page 49: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

49

Extras - GUI Tack

Output from JOptionPane.showConfirmDialog

Page 50: Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.

50

Extras - GUI Track

Moreoutput