Download presentation
Presentation is loading. Please wait.
1
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 Around and around …
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 See the difference ?
10
Looping Control Flow Loop 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
Phases of loop execution
Looping Control Flow loop entry loop test each time executed is an iteration 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
How many times does this loop execute?
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
How many times does this loop execute?
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 Calculating square root
Eevent: guess is good enough Initialize: set goodEnough to false Test: while (!goodEnough) Re-evaluate set goodEnough to (square - guess*guess) < some threshold
17
Looping Control Flow public 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
Devices used for file storage
File Input/Output Devices used for file storage
19
File Input/Output
20
advantages of using files?
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
22
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
23
File Input/Output import.java.io.*; input data output data disk file
“myInfile” disk file “myOutfile” executing program your variable (of type Scanner) your variable (of type PrintWriter)
24
File Input/Output All the Scanner methods can be applied to inFile
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 exceptions public static void main(String args[]) throws IOException Passes the exception to the next level See Chapter 7 for how to handle it ourselves
27
File Input/Output What 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 the difference between constructors for input
and output files ?
29
Loops and Files Read exactly 100 blood pressures from a file
Count-controlled loop Read all the blood pressures from a file no matter how many are there End-of-file controlled loop Read blood pressures until a dangerously high BP (200 or more) is read Flag-controlled loop Sentinel-controlled loop Read blood pressures until a negative value is found
30
Count-Controlled loop
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
End-of-file controlled loop
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.hasNextLine(); <EOF> (returns true)
33
Flag-controlled loop 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
Sentinel-controlled loop
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 loop Counting Summing
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
What condition ends the loop? How should the condition be initialized? How should the condition be updated? What is the process being repeated? How should the process be initialized? How should the process be updated? What is the state of the code on exiting the loop?
40
How to Design Loops Key Phrase Termination condition
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? ?
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 Loops is in class Character isUpperCase Open file for reading
while NOT EOF Read line CountUpperCase Set count to 0 Set index to 0 while index < line.length() letter = line.charAt(); if isUpperCase(letter) Increment count increment index isUpperCase is in class 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
CountUCL was tested with 3. Can you
Testing Loops Should test a loop for four special cases: Loop is skipped entirely Loop body executes just one Loop executes some normal number of times Loop fails to exit CountUCL was tested with 3. Can you design cases for 1, 2, and 4?
49
Output from JOptionPane.showConfirmDialog
Extras - GUI Tack Output from JOptionPane.showConfirmDialog
50
Extras - GUI Track More output
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.