1 / 60

Chapter 5 File Objects and Looping Statements

Chapter 5 File Objects and Looping Statements. Chapter 9 Topics. Using Data Files for I/O While Statement Syntax Count-Controlled Loops Event-Controlled Loops Using the End-of-File Condition Using a While Statement for Summing and Counting Nested While Loops

wauna
Download Presentation

Chapter 5 File Objects and Looping Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 5 File Objects and LoopingStatements

  2. Chapter 9 Topics • Using Data Files for I/O • While Statement Syntax • Count-Controlled Loops • Event-Controlled Loops • Using the End-of-File Condition • Using a While Statement for Summing and Counting • Nested While Loops • Loop Testing and Debugging

  3. To Use File I/O, you must • Import package java.io.* • Choose valid identifiers and types for your file variables and declare them • Instantiate a file object for each file variable • Use your file identifiers in your I/O statements (using available methods such as readLine, print, println) • Closethe files when through

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

  5. input data output data Using files for I/O import.java.io.*; disk file “myInfile.dat” disk file “myOutfile.dat” executing program your variable (of type BufferedReader) your variable (of type PrintWriter)

  6. readLine() method • readLine() method of BufferedReader class uses no parameters and returns an object of class String. • It reads a line of input from the file, including the end-of-line mark, discards the EOL mark, and returns the rest of the line String line; line = inFile.readLine();

  7. How do you read a number? Read a string and convert it to a number int numberOfDependents; line = inFile.readLine(); numberOfDependents = Integer.parseInt(line); double taxRate; line = inFile.readLine(); taxRate = Double.parseDouble(line);

  8. print() and println() methods • print() writes its parameters on the file to which the method is applied • println() is just like print, but it appends an end-of-line before returning. Sound familiar? print and println in class PrintWriter behave exactly the same as those methods of the same name we have used with System.out

  9. I/O Methods and Exceptions • An exception is an unusual situation detected while a program is running; it halts the normal execution of the method • Java recognizes two types of exceptions, checked and unchecked • Unchecked exceptions can be ignored, but checked exceptions must be explicitly recognized by the program

  10. Forwarding an exception • An exception can be forwarded by adding a throws clause to a method heading. The clause specifies the name of the exception that is being forwarded public static void main(String[ ] args) throws IOException • The exception is passed to the method’s caller, until an exception handler is found, or passing terminates with the JVM

  11. IOException • BufferedReader and FileWriter classes throw an exception called IOException. • PrintWriter does not throw any exceptions, but the PrintWriter constructor must be passed a FileWriter object that can throw an IOException • More about exceptions in Chapter 9

  12. What is a loop? • A loop is a repetition control structure • It causes a single statement or block to be executed repeatedly while an expression is true

  13. Two types of loops count-controlled loops repeat a specified number of times event-controlled loops something happens inside the loop body that causes the repetition to stop

  14. While Statement while ( Expression) { . . // loop body . } NOTE: Loop body can be a single statement, a null statement, or a block

  15. When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the loop body WHILE LOOP false Expression true body statement

  16. Count-controlled loops contain • An initialization of the loop control variable • An expression to test for continuing the loop • An update of the loop control variable to be executed within each iteration of the body

  17. Count-controlled Pattern int loopCount; // Declare loop variable loopCount = 1; // Initialize loop variable while (loopCount <= 10) // Test expression { . // Repeated actions . . loopCount = loopCount++; // Update loop variable }

  18. Count-controlled Example int count; // Declare loop variable count = 1; // Initialize loop variable while (count <= 4) // Test expression { // Repeated action System.out.println(“count is “ + count); count ++;// Update loop variable } System.out.println(“Done”);

  19. count Count-controlled loop int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println(“Done”); OUTPUT

  20. count 1 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT

  21. count 1 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT

  22. count 1 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1

  23. count 2 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1

  24. count 2 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1

  25. count 2 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2

  26. count 3 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2

  27. count 3 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2

  28. count 3 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3

  29. count 4 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3

  30. count 4 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3

  31. count 4 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count is 4

  32. count 5 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count is 4

  33. count 5 int count; count = 1; while ( count <= 4 ) { FALSE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count is 4

  34. count 5 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count is 4 Done

  35. Count-Controlled Loop Example • dataFile contains 100 blood pressures, one to a line • Use a while loop to read the 100 blood pressures and find their total

  36. // Count-controlled loop int thisBP; int total; int count; count = 1; // Initialize total = 0; while (count <= 100) // Test expression { thisBP = Integer.parseInt(dataFile.readLine()); total = total + thisBP; count++; // Update } System.out.println(“The total = “ + total);

  37. Event-controlled loops • Sentinel controlled Keep processing data until a special value which is not a possible data value is entered to indicate that processing should stop • End-of-file controlled Keep processing data as long as there is more data in the file • Flag controlledKeep processing data until the value of a flag changes in the loop body

  38. Examples of kinds of loops 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

  39. A sentinel-controlled loop • Requires a “priming read” • “Priming read” means you 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

  40. // Sentinel is negative blood pressure. int thisBP; int total; int count; count = 1; // Initialize total = 0; // Priming read thisBP = Integer.parseInt(dataFile.readLine()); while (thisBP > 0) // Test expression { total = total + thisBP; count++; // Update thisBP = Integer.parseInt(dataFile.readLine()); } System.out.println(“The total = “ + total);

  41. An end-of-file controlled loop • depends on fact that readLinereturns null if there is no more data

  42. // Read and sum until end of line int thisBP; int total; int count; count = 1; // Initialize total = 0; String line; line = dataFile.readLine(); while (line != null) // Test expression { thisBP = Integer.parseInt(line); total = total + thisBP; count++; // Update line = dataFile.readLine(); } System.out.println(“The total = “ + total);

  43. Flag-controlled loops • Use meaningful name for the flag • Initialize flag (to true or false) • Test the flag in the loop test expression • Change the value of the flag in loop body when the appropriate condition occurs

  44. A flag-controlled loop • Count and sum the first 10 odd numbers in a data file • Initialize flag notDone to true • Use while(notDone) for loop test • Change flag to false when 10 odd numbers have been read or if EOF is reached first

  45. count = 0; sum = 0; notDone = true; while ( notDone ) { line = dataFile.readLine( ); // Get a line if (line != null) // Got a line? { number = Integer.parseInt(line); if (number % 2 == 1) // Is number odd? { count++; sum = sum + number; notDone = ( count < 10 ); } } else // Reached EOF unexpectedly { errorFile.println(“EOF reached before ten odd values.”) notDone = false; // Change flag value } }

  46. Loops often used to • Count all data values • Count special data values • Sum data values

  47. // Flag and EOF controlled loop countGoodReadings = 0; // Initialize isSafe = true; while (isSafe && (line = dataFile.readLine() != null)) { thisBP = Integer.valueOf(line).intValue(); if (thisBP >= 200) isSafe = false;// Change flag else countGoodReadings++; // Update } System.out.println(“There were ” + countGoodReadings + “ safe blood pressure readings.”);

  48. Pattern of a nested loop initialize outer loop while ( outer loop condition ) { . . . initialize inner loop while ( inner loop condition ) { inner loop processing and update } . . . }

  49. Nested loop design • Begin with outer loop • When you get to where the inner loop appears, make it a separate module and come back to its design later

  50. Algorithm uses Nested Loops • Get a data line from the data file • While more data • obtain starCount from the data line • use a count-controlled loop to print starCount asterisks to the output file • print a newline character to the output file • read next data line from the data file • Print “End” to the output file

More Related