我不确定为什么会收到此错误。当我运行程序时,我得到了

java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)


我只运行一台扫描仪,并且在此while循环后关闭。我很好奇是否有人可以给我一个提示,告诉我我应该如何将它加五个。这是一些代码。我还对第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;

最佳答案

发生此错误的原因有两个。


在调用nextDouble()之前,您没有检查是否有足够的输入。
hasNext()检查下一个标记,但不会通过调用nextDouble()递增。您要使用hasNextDouble()


您应该将nextDouble()包装在while循环中,并在每个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.
  }
}

关于java - java.util.NoSuchElementException来源不明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49140520/

10-09 09:04