我不知道为什么我会收到这个错误。当我运行我的程序时,我得到了这个
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
我只运行一台扫描仪,并在此循环后关闭。我很好奇是否有人能给我一个关于我应该怎么做的提示。这是一些代码。我还在第27行发表评论,因为那是我认为错误发生的地方。
try {
File file = new File("src/text.txt");
File finalGrades = new File("src/nextText.txt");
PrintWriter output = new PrintWriter(finalGrades);
File finalGradesReport = new File("src/nextTextReport.txt");
PrintWriter output2 = new PrintWriter(finalGradesReport);
Scanner input = new Scanner(file);
double totalPointsAvailable = input.nextDouble();
double homeworkWeight = input.nextDouble() / totalPointsAvailable;
double projectsWeight = input.nextDouble() / totalPointsAvailable;
double firstExamWeight = input.nextDouble() / totalPointsAvailable;
double secondExamWeight = input.nextDouble() / totalPointsAvailable;
double finalExamWeight = input.nextDouble() / totalPointsAvailable;
int numA = 0, numB = 0, numC = 0, numD = 0, numF = 0, numStudents = 0;
double totalPercGrades = 0, averageGrades = 0;
while (input.hasNext()) {
double hw = input.nextDouble() * homeworkWeight;
double pw = input.nextDouble() * projectsWeight; //line 27
double firstEx = input.nextDouble() * firstExamWeight;
double secondEx = input.nextDouble() * secondExamWeight;
double finalEx = input.nextDouble() * finalExamWeight;
答案 0 :(得分:1)
错误发生有两个原因。
在致电nextDouble()
之前,您没有检查是否有足够的输入。
hasNext()
检查下一个令牌,但不会通过调用nextDouble()
来增加。您想使用hasNextDouble()
你应该在while循环中包装nextDouble()
并在每个nextDouble()
之前使用一个计数器或只是一个条件来确保你的文件中有一个双重标记并跟踪你的位置在文件中
应该使用类似的东西:
//...below Scanner input = new Scanner(file);
int tokenCounter = 0;
//This will set all of your variables on static fields.
while (input.hasNextDouble()) { /* <-- this wraps your nextDouble() call */
setVariables(input.nextDouble(), tokenCounter++);
}
//several lines of code later
public static void setVariables(double inputValue, tokenCounter){
switch(tokenCounter){
case 0: totalPointsAvailable = inputValue; break;
case 1: homeworkWeight = inputValue; break;
case 2: projectsWeight = inputValue; break;
//Continue the switch/case based on the expected order of doubles
//and make your variables static sense they seem changes to your code might
//cause you to break up your main method and static variables will be easier
//to access across different methods.
}
}