Chapter 6
Loops and Files
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
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
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
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
6
Looping Control Flow
Aroundand
aroundand…
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
8
Looping Control Flow
9
Looping Control Flow
Seethe
difference?
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
11
Looping Control Flowloop entry
each time executedis an iteration
loop test
exited the loop Expression is false
Phases of loop execution
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)
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?
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?
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
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
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; }}
18
File Input/Output
Devices used for file storage
19
File Input/Output
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?
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
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
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.*;
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
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
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
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
28
File Input/Output
See thedifferencebetween
constructorsfor input
andoutputfiles
?
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
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
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
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)
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
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
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
36
Loops and Files
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
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?
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?
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? ?
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? ?
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? ?
43
Nested Loops
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!
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
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
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(); }
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?
49
Extras - GUI Tack
Output from JOptionPane.showConfirmDialog
50
Extras - GUI Track
Moreoutput