/* 9/25/2019 * * introduce input files * Must put the following 2 things: * (a) import the java.io pkg * (b) put "throws IOException" * for input files, use 2 classes * File and Scanner */ import java.util.Scanner; import java.io.*; /** In version 2 of ReadGrades, we use a variable for filename, show how to do in 1 stmt, * show how to check if file exists */ public class ReadGradesV2 { /** main reads in a number of grades from an input file * NOTE: we have 2 Scanner objects, one is connected to an input file, and the other * to the keyboard */ public static void main(String[] args) throws IOException { // create a Scanner object and connect to keyboard Scanner keyboard = new Scanner(System.in); System.out.println("Enter file name for input file: "); String filename = keyboard.next(); // create a File object File infile = new File(filename); // create a Scanner object and connect it to the File object // Scanner dataFile = new Scanner(new File(filename)); if (!infile.exists()) { // exists is a method in the File class and it checks whether a // file can be found. System.out.println("No file with the name " + filename + " can be found."); System.exit(1); // terminate the program exit FAILURE } Scanner dataFile = new Scanner(infile); // now we can use all the methods of the Scanner class int grade; while (dataFile.hasNextInt()) { // reads until EOF only if there are integers grade = dataFile.nextInt(); System.out.println("grade read in: " + grade); } // close both Scanner objects keyboard.close(); dataFile.close(); } }