1 / 57

Chapter 4 LOOPS AND FILES CONT’D

Chapter 4 LOOPS AND FILES CONT’D. 1. 1. SENTINEL-CONTROLLED LOOPS. Suppose we did not know the number of grades that were to be entered. Maybe, a single program is to be used for classes of varying sizes. We can use a sentinel-controlled loop to solve the problem. 2. 2.

chiku
Download Presentation

Chapter 4 LOOPS AND FILES CONT’D

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 4LOOPS AND FILES CONT’D 1 1

  2. SENTINEL-CONTROLLED LOOPS Suppose we did not know the number of grades that were to be entered. Maybe, a single program is to be used for classes of varying sizes. We can use a sentinel-controlled loop to solve the problem. 2 2

  3. SENTINEL-CONTROLLED LOOPS A sentinel is a special value, outside the range of expected inputs, which is used to signal that there is no more data to be entered. A sentinel-controlled loop continues to iterate as long as the sentinel value has not been read. 3 3

  4. SENTINEL-CONTROLLED LOOPS The program AvgOfGradesUsesSentinel.java is a another program to calculate and display the average of the grades entered by the user. The program will work for any number of grades (including 0). The grade –999 is used as a sentinel value. The user is asked to enter this value after the last grade is entered to signal the end of input. *** See the program AvgOfGradesUsesSentinel.java on webct 4 4

  5. SENTINEL-CONTROLLED LOOPS In the program AvgOfGradesUsesSentinel.java we read the first grade before the loop so that grade has a value for the initial evaluation of the continuation expression. This type of read is called a priming read. This read is outside the loop so it will not be repeated. Notice there is another read at the bottom of the loop to get the next value of grade before the subsequent evaluation of the continuation expression. We will not add the sentinel value -999 to total, because the test to determine whether the sentinel has been entered is between the read and the processing of the input value. 5 5

  6. SENTINEL-CONTROLLED LOOPS To calculate the average in AvgOfGradesUsesSentinel.java, we divided total by gradeCount. The variable gradeCount contains the actual number of the grades that were added to total. Notice that we don’t make gradeCount equal to 1 until we have added the first grade to total. 6 6

  7. ANOTHER CONDITIONAL LOOP *** See the program CalcGrossPayOfEmployees.java on webct 7 7

  8. NESTED LOOPS ***See the program CalcGrossPayOfEmployeesWInputVal.java on webct 8 8

  9. NESTED LOOPS It is possible to have a loop inside a loop. We call this nesting of loops. Nested loops are useful in situations where we need to repeatedly perform a repetitive operation. The inner loop of a nested loop goes through all of its iterations for each iteration of the surrounding loop. 9 9

  10. NESTED LOOPS Problem: Write a pseudocode algorithm for a program that calculates and displays the annual income for each of a company’s three divisions and the annual income for the company as a whole using the monthly incomes of each division that are entered by the user. 10 10

  11. NESTED LOOPS ***See the program IncomeByDivision.java on webct 11 11

  12. NESTED LOOPS Problem: Trace the program NestedForLoops.java by hand to figure out what is displayed when it is executed. 12 12

  13. THE break STATEMENT The break statement causes a loop to terminate. When a break statement is encountered inside a loop, execution immediately goes to the first statement following the loop. When a break statement is encountered multiple levels deep inside a nested loop, only the loop immediately surrounding the break is exited. If a break is in a switch statement in a loop, the break exits only the switch not the loop. 13 13

  14. THE continue STATEMENT The continue statement causes a loop to stop its current iteration and begin the next iteration. In a while or do-while loop this means that the execution automatically goes to the evaluation of the continuation expression. If the expression is true, the next iteration begins. In a for loop, this means the execution automatically goes to the update portion of the loop header. The update is executed and then the continuation expression is evaluated. If the expression is true, the next iteration begins. 14 14

  15. THE break AND continue STATEMENTS Avoid using the break and continue statements in loops. They make it more difficult to follow the logic of the program. You may only use the break in this class in a switch statement. You may not use the continue in this class. 15 15

  16. OTHER FORMS OF THE UPDATE EXPRESSION The update of a loop counter does not have to be ++. There are some situations where it is more natural to count backwards, so we might initialize a counter to a value at the top end of a range and decrease its value by using --. We might want to count upward or downward by some value other than one, so we might use the += or the -= operator for our update. *** See Other Forms of the Update Expression in Section 4.5 of the text *** See Checkpoint questions 4.9c, 4.11, & 4.12 on pages 198 - 199 of the text and Algorithm Workbench questions 3 and 10 on pages 231 - 232 of the text 16 16

  17. WHICH LOOP SHOULD YOU USE? A repetitive algorithm can be implemented using any of the three loops: while, do-while, or for. The for loop is well suited to situations where the exact number of iterations is known. The initialization, continuation, and update can be specified inside the parentheses at the top of the loop. The for loop was designed to simplify the writing of count-controlled loops. The do-while loop is ideal for situations where you want the loop to iterate at least once. The while loop is ideal for situations where you do not want the loop to iterate if the condition is false from the beginning. Sentinel-controlled loops and loops that read an unknown number of items from a file can be more elegantly encoded using a while loop. 17 17

  18. INTRODUCTION TO FILE INPUT AND OUTPUT The programs we have studied so far have received a small amount of input data from the user, performed a few calculations, and displayed the values of a few data items in a console window or dialog box. Once the console window clears or the dialog box is closed, the output is lost. When the program stops executing or the computer loses power, the data in the variables is lost. In many applications, we need to store data longer term, for reference or additional processing. Data can be stored in a file on some secondary storage device and retrieved for later use. 18 18

  19. INTRODUCTION TO FILE INPUT AND OUTPUT An output file is a file a program writes data to. An input file is a file a program reads data from. 19 19

  20. INTRODUCTION TO FILE INPUT AND OUTPUT There are two general types of files: text and binary. A text file contains data that has been encoded as text, using some encoding scheme, like Unicode. Even the numbers in a text file are encoded as a series of characters. Text files can be viewed using a text editor like Notepad. A binary file contains data that has not been converted to text. You cannot view the contents of a binary file with a text editor. In this class you will be introduced to text files. 20 20

  21. INTRODUCTION TO FILE INPUT AND OUTPUT The Java API provides a number of classes that we can use to work with files. To use these classes, you must include the following import statement at the top of your source file, before any classdefinitions. import java.io.*; 21 21

  22. INTRODUCTION TO FILE INPUT AND OUTPUTCreating an Object of the Fileclass To use a file in your program, you will create an instance of the Fileclass. Pass the name of the file, as a string, to the constructor of the Fileclass. Example: The statement below creates a File object that represents a file named MyData.txt and a variable named file that references this object. File file = new File("MyData.txt"); Pass the name of the file to the File class’s constructor. 22 22

  23. INTRODUCTION TO FILE INPUT AND OUTPUTCreating an Object of the Fileclass In the previous example the File object created represented a file named MyData.txt in the current working directory/folder. The current working directory is the location where the program is being run from. To specify a file in another directory we must include path information. For example, for a file named MyData.txt on the H drive of a computer in a folder called CS1336 we could write: File file = new File("H:/CS1336/MyData.txt"); 23 23

  24. INTRODUCTION TO FILE INPUT AND OUTPUTCreating an Object of the Fileclass It is also possible to pass a reference to a String object containing the name of the file to the constructor of the Fileclass. Example: In the following segment we let the user enter the name of the file. String fileName; System.out.println("Enter the name of the file."); fileName = keyboard.nextLine( ); File file = new File(fileName); 24 24

  25. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File When you want to write data to a file to save it, you will create an instance of the PrintWriterclass. 25 25

  26. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File Example: The statement below creates, opens, and links the file referenced by file with the PrintWriter object that is referenced by the variable named outputFile. Here we are calling the constructor of the PrintWriterclass and passing it the variable that references a File object. This presumes that the File object referenced by file was previously created. PrintWriter outputFile = new PrintWriter(file); Warning: if the file already exists, it will be erased and replaced with a new file. Pass the reference to the File object to the constructor of the PrintWriter class. 26 26

  27. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File Once you have opened the file by creating an object of the PrintWriterclass, you can write data to the file using the print, println, and/or printf methods of this object. You already know how to use the print, println, and printf methods of the System.out object to display data in a console window. They are used in the same way with a PrintWriter object to write data to a file. 27 27

  28. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File For example, the println statement below writes the value stored in the variable realNumber (2.55) followed by a newline character to the file connected to the PrintWriter object referenced by outputFile. double realNumber = 2.55; outputFile.println(realNumber); 28 28

  29. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File Data is written to a file as a continuous stream of characters. 29 29

  30. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File Example: double realNumber = 2.55, rate; outputFile.println(realNumber); outputFile.print("Hello class.\n"); rate = 6.55 + realNumber; outputFile.printf("The rate is $%,.2f.\n", rate); The data above is written to the file linked with outputFile as: 2.55<newline>Hello class.<newline>The rate is $9.10.<newline> We are representing the newline character with <newline>. The newline character separates or delimits the individual data items. Later, you will see that the individual data items must be separated in order for a program to read them from the file. 30 30

  31. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File Since what we are writing is a text file, we can look at the file using a text editor like notepad. A text editor interprets the newline character as a command to go to the next line. When you open the file created in Notepad you will see the following: 31 31

  32. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File After you are done using a file you must close it using the close member method of the PrintWriter object. Example: outputFile.close( ); The PrintWriter object has a close member method. 32 32

  33. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File Most operating systems temporarily write output destined for a file to a file buffer in the computer's main memory. When the buffer is filled, the contents of the buffer are written to the file. This improves system performance since interaction with secondary storage is slower than main memory. The close method writes any data that is still in the buffer to the file. Until you close the file, your data may not be in the file on the nonvolatile secondary storage device. Also, many operating systems limit the number of files a program/process can have open at one time. Close the files you have finished with, so that you will be allowed to open other files when you need to. Once the file is closed, the connection between the file and the PrintWriter object is removed. 33 33

  34. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File In Java, many run-time errors are called exceptions. We say that a Java program throws an exception when certain errors occur. For this course we will think of an exception as a signal that the program cannot continue unless the problem is dealt with. For example, if you try to create a PrintWriter object to create a file, but the file cannot be created, the PrintWriter object throws an exception of the IOException type. 34 34

  35. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File When an exception is thrown, the executing method can either deal with the exception or throw it again. If the main method throws an exception, the program terminates and an error message is displayed. In this class, we will simply allow our methods to rethrow any exceptions that occur. 35 35

  36. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File To allow a method to rethrow an exception we write a throws clause in the method header. An example of this is shown in the main method header below: public static void main(String[ ] args) throws IOException 36 36

  37. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File Any method that creates a PrintWriter object or any method that calls a method that creates a PrintWriter object and does not deal with the problem signaled by the exception must have this throws clause in its header. Otherwise, the program will not compile. 37

  38. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File If the file you create with a PrintWriter object already exists, the file will be erased and an empty file will be created. 38 38

  39. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File If you don't want to erase the file if it already exists, test whether the file exists before creating the PrintWriter object. You can test if a file exists by using the exists member method of an object of the File class. The exists method returns true if the file exists. The exists method returns false if the file does not exist. 39 39

  40. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File In SimpleFileOutput.java we use the exists member method of a File object to make sure we do not erase the file MyData.txt if it already exists. *** See the program SimpleFileOutput.java on webct 40 40

  41. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File In SavePlayerStats.java the user enters the name of the output file. When the name of an existing file is entered, the user gets to choose between overwriting the existing file or entering the name of another file. ***SavePlayerStats.java is available on webct 41 41

  42. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the PrintWriterclass to Write Data to a File To write data to a text file: 1. Include the statement import java.io.*; before the class definitions of your source file. 2. Put the throws IOException clause in the method header of any method that creates a PrintWriter object or calls a method that creates a PrintWriter object. 3. Create an object of the Fileclass in memory. Pass the name of the file as the argument to the constructor. 4. Test if the file already exists using the File objects exists member method. Proceed to step 5 only when the file does not exist or it is ok to overwrite the contents of the file. 5. Create a PrintWriter object in memory. Pass the File reference variable as the argument to the constructor of the PrintWriter class. The file will be created, linked with the PrintWriter object, and opened for writing. 6. Use the PrintWriter object's member methods println, print, and/or printf to write data to the file. 7. Use the PrintWriter object's close member method to close the file. 42 42

  43. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File Previously, we read data entered at the keyboard using an object of the Scannerclass. We can also use an object of the Scanner class to read data from a file. 43 43

  44. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File Include the following two import statements at the top of your source file, before your class definitions, so that you can use the File and Scanner classes. import java.io.*;import java.util.Scanner; 44 44

  45. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File Create an instance of the Fileclass to represent the input file. Example: The statement below creates a File object that represents a file named MyData.txt and a variable named aFile that contains the address of the File object. File aFile = new File("MyData.txt"); 45 45

  46. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File Use the File object’s exists member method to see if the input file exists before creating the Scanner object to open the file. It is an error to open a file that does not exist for input. Java throws an IOException if this occurs. 46 46

  47. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File Once we know that the file exists, we create and instance of the Scannerclass and link it with the file. For example, assuming aFile has already been created and represents the input file, the following statement, creates an instance of the Scannerclassand opens the file represented by aFile to supply input to the program. We can read from the file via the Scanner reference variable inputFile. Scanner inputFile = new Scanner(aFile); 47 47

  48. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File The Scannerclass throws an IOException if the file passed as the argument to its constructor cannot be opened. Any method that passes a File object reference to the Scanner class’s constructor must have the throws IOException clause in its method header. Any method that calls a method that does this also needs this clause. 48 48

  49. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File Once you have opened a file for input using the Scanner class’s constructor you can read data from the file using the member methods of the Scanner object. *** See Table 2-17 of the text For example, you can use the method nextLine to read a string of characters, use the nextInt method to read an integer, use the nextDouble method to read a double, etc. 49 49

  50. INTRODUCTION TO FILE INPUT AND OUTPUTUsing the Scannerclass to Read Data from a File When a file is opened for input, the read position is the first byte of the file. We will read from a file in a sequential manner. As data is read, the read position advances through the file. Reading from a file does not remove data from the file, we are simply copying the data into the variables of our program. 50 50

More Related