我正在尝试从 .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));
关于java - 尝试从文件读取整数时出现 NoSuchElementException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35448527/