gpt4 book ai didi

来源不明的 java.util.NoSuchElementException

转载 作者:行者123 更新时间:2023-12-02 11:33:10 26 4
gpt4 key购买 nike


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

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;

最佳答案

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

  1. 在调用 nextDouble() 之前,您没有检查是否有足够的输入。

  2. 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.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49140520/

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