gpt4 book ai didi

Java 循环困惑

转载 作者:行者123 更新时间:2023-12-01 11:03:30 25 4
gpt4 key购买 nike

我编写了这段代码,旨在读取具有整数值的文件。如果整数值 >= 0 且 <=100,我需要给出成绩的平均值。如果有任何值超出指定范围 0-100,那么我需要计算不正确的整数等级,通知用户不正确的等级,并告知有多少不正确的等级。我尝试了该代码,但我不断收到错误代码:

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.");
}


}

}

最佳答案

您正在执行一次检查hasNext,但随后您使用nextInt()next()从扫描仪读取两次。

关于Java 循环困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33154843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com