繁体   English   中英

尝试从文件读取整数时出现NoSuchElementException吗?

[英]NoSuchElementException when trying to read integers from a file?

我正在尝试从.txt文件读取整数,即使while循环包含hasNextInt来确保要读取的文件中还有另一个整数,我也会在输入后直接收到此错误。

import java.util.Scanner;
import java.io.*;

public class Part2 {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String prompt = ("Please input the name of the file to be opened: ");
    System.out.print(prompt);
    String fileName = input.nextLine();
    input.close();
    Scanner reader = null;

    try{
      reader = new Scanner(new File(fileName)); 
    }

    catch(FileNotFoundException e){
      System.out.println("--- File Not Found! Exit program! ---"); 
    }

    int num = 0;
    while(reader.hasNextInt()){
      reader.nextInt();
      num++;
    }

    int[] list = new int[num];
    for(int i = 0; i<num; i++){
      list[i] = reader.nextInt(); 
    }

    reader.close();

    System.out.println("The list size is: " + num);
    System.out.println("The list is:");
    print(list);//Method to print out
    }//main
}//Part2

这是因为在while循环中,您已到达文件末尾。

 while(reader.hasNextInt()){
          reader.nextInt();
          num++;
        }

尝试在while循环之后再次将其重新初始化。

 reader = new Scanner(new File(fileName));

我认为最好像这样使用List

List list = new ArrayList();
int num = 0;
while(reader.hasNextInt()){
  list.add(reader.nextInt());
  num++;
}

/* this part is unnecessary
int[] list = new int[num];
for(int i = 0; i<num; i++){
  list[i] = reader.nextInt(); 
}
*/
//then
System.out.print(list);

暂无
暂无

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

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