简体   繁体   中英

Read text file for integers and storing to array using scanner and exceptions

I'm trying to loop through a text file for integers and store integers found into an array.

Using a try-catch to determine which words are integers and which are not using InputMismatchException, removing the non-int strings from the input stream. As well as a NoSuchElementException for blank lines in the file. My main issue is storing the integers and printing those integers in the array, in my second method :o . It also appears my loop is also recording non-ints as null as well. They aren't suppose be stored into the array.

public static void main(String[] commandlineArgument) {
      Integer[] array = ReadFile6.readFileReturnIntegers(commandlineArgument[0]);
      ReadFile6.printArrayAndIntegerCount(array, commandlineArgument[0]);
   }

   public static Integer[] readFileReturnIntegers(String filename) {
      Integer[] array = new Integer[1000];
      // connect to the file
      File file = new File(filename);
      Scanner inputFile = null;
      try {
         inputFile = new Scanner(file);
      }
      // If file not found-error message
      catch (FileNotFoundException Exception) {
         System.out.println("File not found!");
      }
      // if connected, read file
      if (inputFile != null) {
      // loop through file for integers and store in array
         while (inputFile.hasNextLine()) {
            for(int i = 0; i<array.length; i++)
            {
               try{
                  array[i] = inputFile.nextInt();
               }
               catch(InputMismatchException excep1)
               {
                  String word = inputFile.next();
               }
               catch(NoSuchElementException excep2){
               }
            }
         }
      }
      return array;
   }

   public static void printArrayAndIntegerCount(Integer[] array, String filename) {
   //prints number of integers from file
   //prints each integer in array
   }
}

Assuming all you logic for reading integers from file are correct and also hoping this is kind of home work. Though the following implementation is not the right approach, it just solves your purpose. All we are doing here is iterating all the elements in the array until it reaches the null and keep writing them into a buffer.

public static void printArrayAndIntegerCount(Integer[] array, String filename) {
   StringBuilder sb = new StringBuilder();
   int count = 0;
   for(Integer i : array) {
      if(i != null) {
          count++;
          sb.append("index = ").append(i).append(", element = ").append(array[i]).append("\n");
      } else {
          break;
      }
   }
   System.out.println("number of integers in file \""+filename+"\" = "+count);
   System.out.println(sb);
}

Replace your catch statement with:

catch(InputMismatchException excep1)
{
      String word = inputFile.next();
      i-=1;
}

You were incrementing the array counter if it found a word . I have run my own test and this worked for me to fix your issue.

 public static void printArrayAndIntegerCount(Integer[] array, String filename) {
       String message = "";
       int i = 0;
       while(i < array.length && array[i]!=null){
           message = message + "index = "+i+", element = "+array[i]+"\n";
           i+=1;
        }
       System.out.println("number of integers in file \""+filename+"\" = "+i);
       System.out.println(message);
}

The approach taken in the first method is a bit flawed, since you're incrementing the i variable whether or not an integer is read.

So for example, if the file looked like this:

4
Hello
5
e
7

The beginning of your array would look like

[4, null, 5, null, 7...]

So you will end up with an array of size 1000, which has nulls at unpredictable places in there.

A slightly better approach would be this:

  • Keep a separate count variable that says how many integers you actually read.
  • Add items to the array at index count and not at i (since i just says how many lines you've looked at, whereas count will tell you how many integers you've come across).
  • When you're finished reading them, either
    • pass the count variable to the method that prints the array (so it knows only to look at the first count items), or
    • just copy the entire array into a new array of size count .

Example incorporating this into your code:

if(inputFile != null) {
    // the number of integers we've read so far
    int count = 0;

    // loop through file for integers and store in array
    while(inputFile.hasNextLine()) {
        for(int i = 0; i < array.length; i++) {
            try {
                array[count] = inputFile.nextInt();
                count++;
            } catch(InputMismatchException excep1) {
                String word = inputFile.next();
            } catch(NoSuchElementException excep2) {
            }
         }
     }
}

Then to copy into a correctly sized array,

Integer[] newArray = new Integer[count];
for(int i = 0; i < count; i++) {
    newArray[i] = array[i];
}

and just return newArray instead of array .

Your print method will then simply have the same signature and functionality you'd expect:

public static void printArrayAndIntegerCount(Integer[] array, String filename) {
    for(int i = 0; i < array.length; i++) {
        // print the number at array[i], and whatever else you want to print
    }
}

This is probably the better approach, as you can still keep all the method signatures the same, and don't need to mess around with returning multiple variables or changing global state.


Or alternatively, if you don't want to copy the relevant bits into a new array, then you could just pass the count variable somehow to your second method, and do something like

for(int i = 0; i < count; i++) {
    System.out.println("\tindex = " + i + ", element = " + array[i]);
}

Key difference there is you're iterating up to count , and not up to array.length .

You would need to find a way to return that from your first method along with the array (or maybe set a static variable somewhere), and you would then need to change the signature of your second method to be

public static void printArrayAndIntegerCount(Integer[] array, int count, String filename) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM