嗨,大家好,我試圖創建一個類型數組的問題,但我想我有一個問題在計算文本文件中的問題, 文本文件有一行空行,然後另一條線則空行等等......我得到一個錯誤:試圖在Java中逐行讀取文件
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) at Question.countQuestions(Question.java:27) at Question.readAllQuestions(Question.java:44) at test.main(test.java:7)
文本文件的例子:
這裏是我的代碼:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Question {
private String q; private String a;
private String b; private String c;
private String d; private String cA;
public Question(String q, String a, String b, String c, String d, String cA) {
this.q = q; this.a = a;
this.b = b; this.c = c;
this.d = d; this.cA = cA;
}
private static int countQuestions() throws FileNotFoundException{
int counter = 0;
Scanner file = new Scanner (new File("testBank.txt"));
while(file.hasNextLine()){
// check if line empty
String text = file.nextLine();
while(!text.equals("")){
file.nextLine();
}
file.nextLine();
file.nextLine();
file.nextLine();
file.nextLine();
file.nextLine();
file.nextLine();
file.nextLine();
file.nextLine();
file.nextLine();
file.nextLine();
counter++;
}
return counter;
}
public static Question[] readAllQuestions() throws FileNotFoundException{
int numberOfQuestions = countQuestions();
Question [] allQuestions = new Question[numberOfQuestions];
Scanner file = new Scanner (new File("testBank.txt"));
for (int i = 0 ; i < allQuestions.length ; i++){
String text = file.nextLine();
String q = "";
while(!text.equals("")){
q += file.nextLine();
}
String a=file.nextLine();
file.nextLine();
String b=file.nextLine();
file.nextLine();
String c=file.nextLine();
file.nextLine();
String d=file.nextLine();
file.nextLine();
String cA=file.nextLine();
file.nextLine();
Question question = new Question(q,a,b,c,d,cA);
allQuestions[i] = question;
}
return allQuestions;
}
內側的內'while'循環你沒有更新的'text',但你是在循環條件使用它,所以評估條件的結果在循環過程中不會改變,這會根據文本在進入循環之前具有的值而永遠循環或不循環。 – SantiBailors