Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Reading Input From A File In addition to reading in values from the keyboard, the Scanner class also allows us to read in numeric values from a file. 1. Create and save a text file (.txt or .dat extension) in the same folder with the .java file. 2. At the very top of your program add the line import java.io.*; //for File and IOException import java.util.Scanner; //for Scanner 3. Add throws IOException after the header of the main method. When working with files, a program may encounter errors that it cannot handle. Examples are the file could be missing when the program tries to open it, or the file’s data may be corrupted. At a minimum, a program must acknowledge that an I/O exception might be thrown. 4. In the main method, create a Scanner object (this one is named reader) to read from a file (this one is named myfile.txt). Scanner reader = new Scanner(new File(“myfile.txt”)); 5. In the main method, create a sentinel-controlled loop. The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to say when the loop is done. In this case, the loop will continue to read from the file until the hasNext() method returns false (when the end of the file has been reached). while(reader.hasNext()) { //statement //statement } 6. Close the scanner object when your program is done using it. reader.close(); reader.hasNext() reader.hasNextLine() reader.hasNextInt() reader.hasNextDouble() Useful Methods Returns true if the scanner has another token in its input Returns true if the scanner has another line Returns true if the next token in the scanner can be interpreted as an int Returns true if the next token in the scanner can be interpreted as a double User input is not part of the AP Java subset. There are many possible ways for supplying user input. If reading input is necessary, it will be indicated in a way similar to the following: double x = call to a method that reads a floating-point number; or double x = IO.readDouble(); // read user input A Sample Program This program reads in numerical data from a file, token by token. Remember, the Scanner object assumes that whitespace characters (spaces, tabs, and new lines) are used to separate the input elements (tokens) from each other. import java.io*; import java.util.Scanner; public class ComputeAverage { //computes the average of the numbers in a file public static void main(String[] args) throws IOException { Scanner reader = new Scanner(new File(“numbers.txt”)); double number, sum=0; int count = 0; //computes the average of the numbers in a file while(reader.hasNext()) { number = reader.nextDouble(); sum += number; count++; } if(count == 0) System.out.println(“The file has no numbers.”); else System.out.println(“The average of “ + count + “ numbers is “ + sum / count); reader.close(); //close the Scanner } } Another Sample Program This program reads in data line by line (the first loop) then reads each line token by token (the nested loop). One scanner is used to read in the lines; a second scanner is used to import java.io*; import java.util.Scanner; public class ComputeAverage { //does something… public static void main(String[] args) throws IOException { Scanner readFile = new Scanner(new File(“numbers.txt”)); Scanner readLine = new Scanner double number, sum=0; int count = 0; //computes the average of the numbers in a file while(reader.hasNext()) { number = reader.nextDouble(); sum += number; count++; } if(count == 0) System.out.println(“The file has no numbers.”); else System.out.println(“The average of “ + count + “ numbers is “ + sum / count); reader.close(); //close the Scanner } } Errors You May Encounter InputMismatchException: This exception can be thrown if you try to get the next token using a next method that does not match the type of the token FileNotFound Exception: Thrown when the file is missing when the program tries to open it Defining Your Own Delimiter By default, the Scanner will read data as tokens separated by whitespace. If you want to read in data separated by something else (comma, colon, etc.) you can create your own delimiter. scan.useDelimiter(",\\s*"); //comma followed by spaces scan.useDelimiter("\\s*dog\\s*"); //space then the word dog then space scan.useDelimiter("/"); //slash A Comma Delimited Program import java.io*; import java.util.Scanner; public class UseCommas { //reads a file of numbers separated by commas public static void main(String[] args) throws IOException { Scanner scan3 = new Scanner(new File(“commadata.txt”)); String line = null; while(scan3.hasNext()) { line = scan3.nextLine(); Scanner scan4 = new Scanner(line); scan4.useDelimiter(", "); //a comma while(scan4.hasNextInt()) { System.out.println(scan4.nextInt()); } } scan3.close(); } }