java - 用户输入 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);
}
}
非常感谢:)
解决方案
首先,它的精度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
推荐阅读
- php - 使用来自 onSubmit 的 PHP 函数返回值作为 HTML 表单中的变量
- c# - if-else 组合框
- python - Pandas:读取 excel nrows 不起作用,并且 dtype 不保留 0 填充
- postgresql - L.timeDimension 以 UTC 的形式向 GeoServer 发送时间而不是 iso8601
- makefile - 在不干扰 -MMD 的情况下覆盖某些目标的隐式规则
- r - 在 ggplot2 中的组级别应用函数
- javascript - 如何使用 pm2 start app.js
- python - 当我将 += 放入字典而不是 = 时出错的原因
- regex - 正则表达式:重用匹配结果以获得相同输出的另一个匹配?
- javascript - 如何判断 KeyboardEvent.key 是可打印字符还是控制字符?