我編寫了這個旨在讀取整數值文件的代碼。如果整數值> = 0和< = 100我需要給出等級的平均值。如果超出指定範圍0-100的任何值,則需要計算不正確的整數等級,通知用戶不正確的等級,並通知有多少不正確的等級。我試圖代碼,但我不斷收到錯誤代碼:Java循環混淆
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Project9.main(Project9.java:26)
代碼示例:
public static void main(String[] args) throws IOException{
String file;
int readInts;
Scanner k = new Scanner(System.in);
System.out.println("Enter filename: ");
file = k.nextLine();
int counterWrong = 0;
int counterRight = 0;
int sum = 0;
double average = 1.0 * sum/counterRight;
File fileReader = new File(file);
if (fileReader.exists()) {
Scanner input = new Scanner(fileReader);
while (input.hasNext()) {
readInts = input.nextInt();
System.out.println(readInts);
String a = input.next();
int a2 = Integer.parseInt(a);
if (a2 <= 100 && a2 >= 0){
counterRight++;
sum = sum + a2;
System.out.println("Score " + a2 + " was counted.");
} else {
counterWrong++;
System.out.println("The test grade " + a2 + " was not scored as it was out of the range of valid scores.");
System.out.println("There were " + counterWrong + " invalid scores that were not counted.");
}
}
if (counterRight > 0){
System.out.println("The average of the correct grades on file is " + average + ".");
}
} else {
System.out.println("The file " + file + " does not exist. The program will now close.");
}
}
}
請告訴我們您正在閱讀 –
您正在閱讀2令牌的文件,而循環,但你只檢查'hasNext()'在一個只有最prbably你沒有留在文件中的任何標記,你仍然用'input.next()'讀取文件在這行之前也檢查一下 – silentprogrammer