Java Reference
In-Depth Information
import java.util.*;
import java.io.*;
Step 2 requires that you create and associate appropriate class variables with the input/
output sources. We already discussed how to declare and associate Scanner objects for
inputting the data from a file. The next section describes how to create the appropriate
objects to send the output to a file.
Step 3 requires us to read the data from the input file using the variables created in Step 2.
Example 3-16 describes how to read the data from a file.
In Step 4, you close the input and output files. To do so, you use the method close ,as
described later in this section.
3
EXAMPLE 3-16
Suppose an input file, say employeeData.txt , consists of the following data:
Emily Johnson 45 13.50
The file consists of an employee's name, the number of hours the employee worked, and
the pay rate. The following statements declare the appropriate variables to read and store
the data into the variables:
//Create and associate the Scanner object to the input source
Scanner inFile = new Scanner( new FileReader("employeeData.txt"));
String firstName;
//variable to store first name
String lastName;
//variable to store last name
double hoursWorked; //variable to store hours worked
double payRate;
//variable to store pay rate
double wages;
//variable to store wages
firstName = inFile.next();
//get the first name
lastName = inFile.next();
//get the last name
hoursWorked = inFile.nextDouble(); //get hours worked
payRate = inFile.nextDouble();
//get pay rate
wages = hoursWorked * payRate;
The following statement closes the input file to which inFile is associated:
inFile.close();
//close the input file
 
Search WWH ::




Custom Search