java - 字符串作为 while 循环中的标记值
问题描述
我正在尝试编写一个程序,询问用户是否要输入实数。如果是,则提示用户输入数字。继续提示输入数字,直到用户说“不”。一旦发生这种情况,输出输入数字的平均值。
我想我一直在尝试为哨兵值实现一个字符串。我希望哨兵值是“否”。但是在我在这里进行的最后一次尝试中,当我输入“是”时,我得到了 InputMismatchException。此外,不确定这是做/当或只是当做的工作。对这一切有点陌生,不知道如何去做,因为我们没有使用字符串作为哨兵的例子。
public static void main(String[] args) {
int count = 0;
float total = 0;
float inputNumber;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = "";
inputNumber = scan.nextFloat();
do {
reply = scan.nextLine();
if (reply.equalsIgnoreCase("yes")) {
System.out.println("Enter a number > ");
total+= inputNumber ;
count++ ;
System.out.println("Enter another number, or " +
"enter \"no\" to terminate > " );
inputNumber = scan.nextFloat();
}
}
while (! reply.equalsIgnoreCase("no")) ;
if (count != 0) {
System.out.println("The average of the numbers is " +
(total / count));
}
}
}
解决方案
- 先删除
inputNumber = scan.nextFloat();
- 修复循环。
scan.nextLine()
之后添加scan.nextFloat()
public static void main(String[] args) {
int count = 0;
float total = 0f;
float inputNumber = 0f;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = scan.nextLine();
while (reply.equalsIgnoreCase("yes")) {
System.out.println("Enter a number > ");
inputNumber = scan.nextFloat();
scan.nextLine();
total += inputNumber;
count++;
System.out.println("Enter another number, or enter \"no\" to terminate > ");
reply = scan.nextLine();
}
if (count != 0) {
System.out.println("The average of the numbers is " + (total / count));
}
}
编辑
public static void main(String[] args) {
int count = 0;
float total = 0f;
float inputNumber = 0f;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = scan.nextLine();
if (!reply.equalsIgnoreCase("yes"))
return;
System.out.println("Enter a number > ");
while (!reply.equalsIgnoreCase("no")) {
reply = scan.nextLine();
try {
inputNumber = Float.parseFloat(reply);
} catch (NumberFormatException e) {
continue;
}
total += inputNumber;
count++;
System.out.println("Enter another number, or enter \"no\" to terminate > ");
}
if (count != 0) {
System.out.println("The average of the numbers is " + (total / count));
}
}
推荐阅读
- scala - 具有基础类型的类型参数 - Scala
- python - 在数据集 PYTHON 上使用正则表达式分隔
- vba - 最后将 Excel 工作表复制到另一个工作簿 (VBA)
- javascript - Discord.js SQLITE_ERROR:表分数没有名为点的列
- tensorflow - Compute Capability 3.0 卡可以运行 Tensorflow 1.8 tensorflow-gpu 运行时吗?
- regex - 使用正则表达式从字符串中提取文件名
- django - 如何在 Django 中将 URL 限制为管理员用户
- javascript - 边距:0 自动;用搜索隐藏另一个 li 元素后
- python - 日历项目没有正确缩进和间距 Python 3
- highcharts - 如何从 Highcharts 中删除注释?