java - NoSuchElementException 不断被触发,我不知道为什么
问题描述
基本上我的程序的目的是从文本文件中选择一个随机引用并根据生成的随机数打印它,该随机数不大于文件中的行数。我知道该文件位于正确的目录中并包含所有内容。
我试过同时使用 while 和 for 循环,但这些似乎是当循环不存在时代码运行没有错误的问题,但没有循环,程序不会做我想要它做的事情。此外,已尝试更改某些变量的范围。
// open file
private static void openFile(){
try {
input = new Scanner(Paths.get("Quotes.txt"));
}
catch(IOException ioException){
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
// get and print quote
private static void printQuote(){
try {
int printQue = randomNumber();
System.out.println(printQue);
for (int i = 0; i < printQue - 1; i++){
input.nextLine();
}
System.out.printf("The randomly selected quote is: %s%n",
input.nextLine());
}
catch(NoSuchElementException elementException){
System.err.println("File formed improperly. Terminating.");
}
catch(IllegalStateException stateException){
System.err.println("Error reading from file. Terminating.");
}
}
// size of list
private static int fileSize(){
try{
int counter = 0;
while (input.hasNext()){
input.nextLine();
counter++;
}
num = counter;
}
catch(NoSuchElementException elementException){
System.err.println("File improperly formed. Terminating");
}
catch(IllegalStateException stateException){
System.err.println("Error reading from file. Terminating.");
}
return num;
}
// get random number
private static int randomNumber(){
int randomNum = random.nextInt(fileSize());
while (randomNum <= 0){
randomNum = random.nextInt(fileSize());
}
return randomNum;
}
打印文本文件中的 100 个引号之一。
解决方案
您的扫描仪正在您的 fileSize() 方法中遍历整个文件,因为您正在调用input.nextLine()
每次迭代。
一旦你到达printQuote()
你已经迭代了整个文件,所以你试图在 (last_index + 1) 处读取一行。