简体   繁体   English

从txt文件读取整数并存储到数组中

[英]Read integers from txt file and storing into an array

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. 我正在使用一个int数组,所以我想在没有列表的情况下执行此操作。 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;
  }

在while循环中将hasNext()更改为hasNextInt()

You might use something like this (to skip over any non-int(s)), and you should close your Scanner ! 您可能会使用类似的方法(跳过所有非整数),并且应该关闭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]);
  }
}

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. 您需要做的是在获取新值并将其放入数组之前,您需要检查以确保它实际上是一个int值,如果不是,则跳过该值,然后移至下一个值值。 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... 另外...正如评论中提到的那样,将整数读为字符串然后从中解析值通常会更容易...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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