Chapter 6 Loops and Files Knowledge Goals Understand

Chapter 6 Loops and Files Knowledge Goals  Understand

Chapter 6 Loops and Files 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 2

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 3 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 4 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

5 Looping Control Flow Around and around and 6 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 7 Looping Control Flow 8 Looping Control Flow

See the difference ? 9 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 10 Looping Control Flow loop entry loop test each time executed is an iteration exited the loop

Expression is false Phases of loop execution 11 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) 12 Looping Control Flow int loopCount; // Declare loop variable loopCount = 1; while (loopCount <= 10) { . . . loopCount++;

} // Initialize loop variable // Test expression // Repeated actions // Update loop variable How many times does this loop execute? 13 Looping Control Flow int count; count = 0;

// Declare loop variable // 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? 14 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 15 Looping Control Flow Calculating square root

Eevent: guess is good enough Initialize: set goodEnough to false Test: while (!goodEnough) 16 Re-evaluate set goodEnough to (square guess*guess) < some threshold 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; } } 17 File Input/Output Devices used for file storage

18 File Input/Output 19 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?

20 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 21 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 import.java.io.*; input data disk file myInfile

your variable (of type Scanner) output data executing program disk file myOutfile your variable (of type PrintWriter)

File Input/Output Scanner in = new Scanner(System.in); Sets up f or k eyb oard FileReader inReader = new FileReader("myInfile"); Scanner inFile = new Scanner(inReader); Se t All the Scanner methods can be applied to inFile

24 up to r ead "my Infi le" File Input/Output Recall that

25 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

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 n ti o p ce el x e

v he xt le t s e se he n s Pa to t 26 See Chapter 7 for how to handle it ourselves 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 27 File Input/Output See the

difference between constructors for input and output files ? 28 Loops and Files Count-controlled loop Read exactly 100 blood

pressures from a file End-of-file controlled loop 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 29 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 } 30

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 31 Loops and Files Use hasNextInt rather than hasNextLine for loop test in.nextInt(); 42 in.hasNextInt();

in.nextInt(); 42 in.hasNextLine(); 32 (returns false) (returns true)

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 } 33 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 34 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 35 Loops and Files 36 Loops and Files Common processes within a loop

Counting 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 37 Any loop that reads and sums all data values Any loop that reads and sums certain values 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? 38 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? 39 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? 40 ? ? ? ? ? ? ? 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? 41 ? ? ? ?

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

42 ? ? ? ? ? ? ? Nested Loops 43 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! 44 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 45 Nested Loops Open 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 46 isUpperCase is in class Character 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(); } 47 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?

48 Extras - GUI Tack Output from JOptionPane.showConfirmDialog 49 Extras - GUI Track More output 50

Recently Viewed Presentations

  • Exploring Biomass

    Exploring Biomass

    , almost 4,000 miles (6,400 km) beneath the Earth's surface. We can dig wells and pump the heated, underground water to the surface. People around the world use geothermal energy to produce electricity, to heat homes and buildings, and to...
  • Global Economy and Extreme Poverty

    Global Economy and Extreme Poverty

    The Water link… To produce 1 lb of MEAT You need 1,000-12,000 lbs of Water! To produce 1 lb of potatoes, wheat, corn and rice You need 60, 108, 168, 229 pounds of water, respectively La simple verdad Según un...
  • Standard Operating Procedures - Case Management

    Standard Operating Procedures - Case Management

    www.agrability.okstate.edu Following the Farm Walk Through, the Counselor or AgrAbility Case Management Liaison will create Summary Report within 14 days, determining if the case is to be a new self-employment outcome or employment retention case.
  • Flame photometry - جامعة الملك سعود

    Flame photometry - جامعة الملك سعود

    1-flame photometry, a branch of atomic spectroscopy is used for determining the concentration of certain . metal ions . such as sodium, potassium, lithium, calcium, Cesium, etc. 2-The . basis of flame photometric working . is that, the types ofmetals...
  • CHAPTER ONE - San Jose State University

    CHAPTER ONE - San Jose State University

    CHAPTER ONE Author: donna.barlow Last modified by ... Interpretation Development of Conclusions Pose New Research Questions Types of Sociological Research Exploratory Research Descriptive Research Explanatory Research Evaluative Research Sociology and Science Ethical Issues in Sociological ...
  • U.s. history

    U.s. history

    Which statement best summarizes the main idea behind the 4th, 5th, and 6th Amendments? Even persons accused of a crime enjoy certain basic rights. Criminal defendants must be fully prosecuted. Criminal acts should lead to the loss of a person's...
  • Cartoon Wars: An Application of Hall&#x27;s Theory to Social ...

    Cartoon Wars: An Application of Hall's Theory to Social ...

    Cartoon Wars: An Application of Hall's Theory to Social Constructs of the Enemy ... United States construct their enemy in political cartoons during times of war and what are the implications of this construct? literature review: wars WWI (1914-1918) U.S,...
  • ATELIER DE TRAVAIL VOLET HOSPITALIER  MISSION SANT PLAN

    ATELIER DE TRAVAIL VOLET HOSPITALIER MISSION SANT PLAN

    Ce plan doit comprendre l'ensemble des activités devant être mises en place par les divers secteurs, de même que . l'arrimage avec les partenaires locaux et régionaux.» Guide . d'opérationnalisation. de la mission Santé du Plan national de la sécurité...