我编写了这个旨在读取整数值文件的代码。如果整数值> = 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