嘿家伙,所以我一直试图回答这个问题几个小时:
编写一个程序,要求用户输入一组浮点值。当 用户输入的值不是数字时,请给用户第二次输入值 。两次机会后,退出阅读输入。添加所有正确指定的值,并在用户输入数据时打印总和。使用异常处理来检测 不正确的输入。在Java中处理异常 - 如何给用户另一个机会?
我试过几个不同的东西,但我总是有同样的问题。一旦输入了不是数字的东西,程序就会输出提示输入另一个输入的消息,但是没有给出机会,也就是说,在输入1个不正确的输入后,它会打印该消息并直接跳转到打印总和。我能做的最好的是在下面,我只是不确定如何解决这个问题。任何帮助是极大的赞赏。
import java.util.Scanner;
import java.util.InputMismatchException;
public class q6{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean firstChance = true;
boolean secondChance = true;
double sum = 0;
while (secondChance){
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
firstChance = false;
}
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
System.out.print("The sum of the entered values is " + sum);
}
}
而不是读一个'double',读一个'String'并使用'Double.parseDouble(String)'。另外,如果你的'firstChance'在try-catch块后面是'true',你应该打破'while循环'。 – 2013-03-14 06:07:27
看着你的问题,你似乎知道逻辑,但它没有反映在代码中。我建议用测试输入干运行此代码,并尝试自己找出问题。您只需确保在给出错误消息 – Shurmajee 2013-03-14 06:09:04