Download presentation
Presentation is loading. Please wait.
Published byRandall Barnett Modified over 9 years ago
1
11 Chapter 4 LOOPS AND FILES CONT’D
2
22 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.
3
33 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.
4
44 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
5
55 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.
6
66 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.
7
77 ANOTHER CONDITIONAL LOOP *** See the program CalcGrossPayOfEmployees.java on webct
8
88 NESTED LOOPS *** See the program CalcGrossPayOfEmployeesWInputVal.java on webct
9
99 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.
10
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.
11
11 NESTED LOOPS ***See the program IncomeByDivision.java on webct
12
12 NESTED LOOPS Problem: Trace the program NestedForLoops.java by hand to figure out what is displayed when it is executed.
13
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.
14
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.
15
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.
16
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
17
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.
18
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.
19
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.
20
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.
21
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 class definitions. import java.io.*;
22
22 INTRODUCTION TO FILE INPUT AND OUTPUT Creating an Object of the File class To use a file in your program, you will create an instance of the File class. Pass the name of the file, as a string, to the constructor of the File class. 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.
23
23 INTRODUCTION TO FILE INPUT AND OUTPUT Creating an Object of the File class 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");
24
24 INTRODUCTION TO FILE INPUT AND OUTPUT Creating an Object of the File class It is also possible to pass a reference to a String object containing the name of the file to the constructor of the File class. 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);
25
25 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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 PrintWriter class.
26
26 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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 PrintWriter class 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); Pass the reference to the File object to the constructor of the PrintWriter class. Warning: if the file already exists, it will be erased and replaced with a new file.
27
27 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File Once you have opened the file by creating an object of the PrintWriter class, 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.
28
28 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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);
29
29 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File Data is written to a file as a continuous stream of characters.
30
30 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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 Hello class. The rate is $9.10. We are representing the newline character with. 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.
31
31 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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:
32
32 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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.
33
33 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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.
34
34 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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.
35
35 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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.
36
36 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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
37
37 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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.
38
38 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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.
39
39 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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.
40
40 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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
41
41 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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
42
42 INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class 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 File class 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.
43
43 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File Previously, we read data entered at the keyboard using an object of the Scanner class. We can also use an object of the Scanner class to read data from a file.
44
44 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class 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;
45
45 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File Create an instance of the File class 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");
46
46 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class 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.
47
47 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File Once we know that the file exists, we create and instance of the Scanner class 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 Scanner class and 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);
48
48 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File The Scanner class 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.
49
49 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class 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.
50
50 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class 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.
51
51 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File When you are done reading from the file, close the file using the Scanner object’s close member method. Example: The statement below closes the file linked with the Scanner object referenced by inputFile. inputFile.close( ); The Scanner object has a close member method.
52
52 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File ***See the program SimpleFileInput.java on webct
53
53 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File Usually, we do not know the exact number of items that are in a file. Objects of the Scanner class have a member method named hasNext that can be used to determine if there is more data in the file. –If there is more data in the file, the hasNext method returns true. –If the end of the file has been reached the hasNext method returns false. We can use the value of the hasNext method to construct a loop that continues to read data from the file until all the data has been read.
54
54 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File ***See the program ReadLines.txt on webct
55
55 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File In ReadLines.java we read each line from the file and stored it as a string of characters. Quite often, a file contains an unspecified number of records. Each record is composed of a number of data fields that relate to a particular entity. Some of the fields contain textual information: names, addresses, titles, etc. Other fields contain numeric information, which we might need to use in calculations. We can use a Scanner object’s methods nextInt, nextFloat, nextDouble, etc. to read and store numeric values so that they can be used in arithmetic expressions.
56
56 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File ***See GetHighBattAvgs.java on webct In GetHighBattAvgs.java we test to make sure there is more data in the file before reading the first data item for each player (the player’s last name). The program that constructed the file wrote complete player records to the file, i.e. we will not run out of data in the middle of a player record.
57
57 INTRODUCTION TO FILE INPUT AND OUTPUT Using the Scanner class to Read Data from a File To read data from a text file: 1. Include the statements import java.io.*; and import java.util.Scanner; before the class definitions of your source file, so that you can use the File and Scanner classes as shown. 2. Put the throws IOException clause in the method header of any method that passes a File reference to the Scanner class’s constructor or calls a method that passes a File reference to a Scanner class’s constructor. 3. Create an object of the File class in memory. Pass the name of the file as the argument to the constructor. 4. Use the File object's exists member method to ensure that the file exists. –Proceed to step 5 only in the case that the file exists. 5. Create a Scanner object in memory. Pass the reference to the File object created above as the argument to the constructor. The file represented by the File object will be opened and linked with the Scanner object. 6. Use the Scanner object's hasNext method to determine whether there is data to be read from the file and then use the Scanner object's member methods nextLine, nextDouble, nextInt, etc. to read data from the file. 7. Use the Scanner object's close member method to close the file.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.