如何管理输入字母而不是数字的用户?

时间:2015-02-22 23:54:52

标签: java exception

我试图编写自动售货机程序,除了告诉它如何处理用户输入字母而不是数字之外,还要做得很好。这是我试图找出的代码块:

System.out.print("Please enter how much money you have to spend (enter -1 to shut down): ");
        double custMoney = scanner.nextDouble();
        if (custMoney <= 0) {
            System.out.println("Thank you for your business!");
            System.exit(0);
        }

如果用户输入的是字母而不是数字,它会给我

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at VendingMachine1.main(VendingMachine1.java:28)

如何解决此问题,以便他们输入信件时会提示他们输入有效的号码?

2 个答案:

答案 0 :(得分:1)

正如@Max所说,您应该将输入作为字符串读取并在用户不是数字时提醒用户,我添加了while(!numberOk),以便用户输入一个字母而不是它会不断询问的数字(或无效数字);)

希望这有助于你

   String custMoney = scanner.next();
    double custMoneyValue;
    boolean numberOk=false;
    while(!numberOk)
    try {
        custMoneyValue = Double.parseDouble(custMoney);
        if (custMoneyValue <= 0) {
            System.out.println("Thank you for your business!");
            numberOk=true;
            System.exit(0); // would make the while loop condition useless...

        }
    }catch (NumberFormatException e) {
            System.out.println("Please insert a number...");
            custMoney = scanner.next();
    }

答案 1 :(得分:0)

以下是double

的一些代码示例
try {
    System.out.print("Enter an integer number: ");
    long i = in.nextLong();
    System.out.print("Thanks, you entered: ");
    System.out.println(i);
    break;
}
 catch (InputMismatchException ex) {
    System.out.println("Error in your input");
    in.next(); // Read and discard whatever string the user has entered
}
相关问题