Read integers from txt file and storing into an array

半城伤御伤魂 提交于 2019-12-25 02:22:40

问题


I'm having issues reading and storing only integers from a text file. I'm using a int array so I want to do this without list. I'm getting a input mismatch exception, and I don't know how I should go about correcting that issue. The text files being read from also include strings.

  public static Integer[] readFileReturnIntegers(String filename) {
     Integer[] array = new Integer[1000];
     int i = 0;
    //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){         
        System.out.print("number of integers in file \"" 
              + filename + "\" = \n");
        //loop through file for integers and store in array     
        while (inputFile.hasNext()) {
           array[i] = inputFile.nextInt();
           i++;
        }
        inputFile.close();
     }
     return array;
  }

回答1:


You might use something like this (to skip over any non-int(s)), and you should close your Scanner!

// if connected, read file
if (inputFile != null) {
  System.out.print("number of integers in file \""
      + filename + "\" = \n");
  // loop through file for integers and store in array
  try {
    while (inputFile.hasNext()) {
      if (inputFile.hasNextInt()) {
        array[i] = inputFile.nextInt();
        i++;
      } else {
        inputFile.next();
      }
    }
  } finally {
    inputFile.close();
  }
  // I think you wanted to print it.
  System.out.println(i);
  for (int v = 0; v < i; v++) {
    System.out.printf("array[%d] = %d\n", v, array[v]);
  }
}



回答2:


Change hasNext() to hasNextInt() in your while loop.




回答3:


What you need to do is before you get a new value and try to put it into the array you need to check to make sure that it is in fact an int and if it isn't then skip over it and move on to the next value. Alternately you could make a string array of all of the values and then copy only the integers into a separate array. However, the first solution is probably the better of the two.

Also... As has been mentioned in the comments it tends to be easier to read the integers in as strings and then parse the values from them...



来源:https://stackoverflow.com/questions/21300584/read-integers-from-txt-file-and-storing-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!