/* * 02199 Programming * Exercise 29: Reading from a file * Author: Torben Gjaldbæk, c9718383 */ import java.util.StringTokenizer; import java.io.*; /* * The main method of this class reads two lines of 10 integers from the file * 'data.txt' (if possible) and stores these in two arrays. * * If a line contains more than 10 integers, the rest of the line (beyond the * first 10 integers) is ignored. * If a line containts fewer than 10 integers, an error message is printed. * If a line containts non-integer types, the rest of the line is ignored and * an error message is printed. * * Finally, the resulting arrays are printed. */ public class IntArrayReader { public static void main (String[] args) { // allocate result arrays int[] array1 = new int[10]; int[] array2 = new int[10]; try { // create input streams FileReader fileReader = new FileReader("data.txt"); BufferedReader inFile = new BufferedReader(fileReader); // count the numbers read from line 1 and 2 int numbersRead1 = 0; int numbersRead2 = 0; // read first line String line = inFile.readLine(); if (line != null) { // use a Stringtokenizer to split the line into tokens StringTokenizer tokenizer = new StringTokenizer(line); try { for (int i = 0; i < 10 && tokenizer.hasMoreTokens(); i++) { String token = tokenizer.nextToken(); int result = Integer.parseInt(token); array1[i] = result; numbersRead1++; } } catch (NumberFormatException exception) { // input could not be converted to integers System.out.println("ERROR: Invalid input (line 1):"); System.out.println(line); System.out.println(); } if (numbersRead1 != 10) { // could not read 10 numbers System.out.println("ERROR: Could not read 10 integers from line 1:"); System.out.println(line); System.out.println(); } // read second line line = inFile.readLine(); if (line != null) { tokenizer = new StringTokenizer(line); try { for (int i = 0; i < 10 && tokenizer.hasMoreTokens(); i++) { String token = tokenizer.nextToken(); int result = Integer.parseInt(token); array2[i] = result; numbersRead2++; } } catch (NumberFormatException exception) { System.out.println("ERROR: Invalid input (line 2):"); System.out.println(line); System.out.println(); } if (numbersRead2 != 10) { System.out.println("ERROR: Could not read 10 integers from line 2:"); System.out.println(line); System.out.println(); } } else { System.out.println("ERROR: Line 2 is empty.\n"); } } else { System.out.println("ERROR: Line 1 is empty.\n"); } // close input stream inFile.close(); // print array 1 System.out.println("Array 1:"); for (int i = 0; i < numbersRead1; i++) { System.out.print(array1[i] + " "); } System.out.println("\n"); // print array 2 System.out.println("Array 2:"); for (int i = 0; i < numbersRead2; i++) { System.out.print(array2[i] + " "); } System.out.println(); } catch (FileNotFoundException exception) { System.out.println("ERROR: The file 'data.txt' was not found."); } catch (IOException exception) { System.out.println(exception); } } }