【发布时间】:2020-01-29 00:25:29
【问题描述】:
我正在尝试编写一个程序,询问用户是否要输入实数。如果是,则提示用户输入数字。继续提示输入数字,直到用户说“不”。一旦发生这种情况,输出输入数字的平均值。
我想我一直在尝试为标记值实现一个字符串。我希望哨兵值是“否”。但是在我在这里进行的最后一次尝试中,当我输入“是”时,我得到了 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));
}
}
}
【问题讨论】:
-
@JohnnyMopp 虽然这是相关的,但主要问题是与此无关。更多的是尝试使用
nextFloat来读取字符串“no”。 -
nextFloat()无法存储字符串。将数字存储为字符串并将其转换为浮点数。 -
@Sweeper 好的,我现在看到了。 OP 有 2 个问题。
标签: java while-loop do-while