首页 > 解决方案 > 用户输入 Java 的平均计算器 - “java.util.NoSuchElementException: No line found”

问题描述

我正在使用 Eclipse 上的用户输入创建一个简单的平均计算器,我收到此错误:“java.util.NoSuchElementException: No line found” at

String input = sc.nextLine();

另外我认为会有后续错误,因为我不确定我是否可以有两个变量 string 和 float 用于用户输入。

import java.util.Scanner;

public class AverageCalculator {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the numbers you would like to average. Enter \"done\"");
        String input = sc.nextLine();
        float num = sc.nextFloat();
        float sum = 0;
        int counter = 0;
        float average = 0;
        while(input != "done"){
            sum += num;
            counter ++;
            average = sum / counter;
        }
        System.out.println("The average of the "+ counter + " numbers you entered is " + average);

    }

}

非常感谢:)

标签: java

解决方案


首先,它的精度float太差了,以至于你使用它对自己造成了伤害。double除非您有非常特殊的使用需求,否则您应该始终使用float.

比较字符串时,使用equals(). 有关更多信息,请参阅“如何在 Java 中比较字符串? ”。

由于您似乎希望用户继续输入数字,因此您需要nextDouble()作为循环的一部分进行调用。而且由于您似乎希望用户输入文本以结束输入,因此您需要调用hasNextDouble()以防止获得InputMismatchException. 用于next()获取单个单词,因此您可以检查它是否是单词"done"

像这样:

Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
    if (sc.hasNextDouble()) {
        double num = sc.nextDouble();
        sum += num;
        counter++;
    } else {
        String word = sc.next();
        if (word.equalsIgnoreCase("done"))
            break; // exit the forever loop
        sc.nextLine(); // discard rest of line
        System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
    }
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);

样本输出

Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0

推荐阅读