public class Calculator
{

    public static void main(String[] args)
    {
        boolean isValid = false;
        Scanner myScanner = new Scanner(System.in);
        String customerType = null;
        System.out.print("Customer Type? (C/R) ");
        customerType = myScanner.next();
        while (isValid == false)
        {
            System.out.print("Enter Subtotal: ");

            if (myScanner.hasNextDouble())
            {
                double sobTotal = myScanner.nextDouble();
                isValid = true;
            }
            else
            {
                System.out
                        .println("Hay! Entry error please enter a valid number");
            }
            myScanner.nextLine();
        }
    }
}


嗨,我是Java的新手,像往常一样,我尝试了Scanner类中的一些操作。

有没有办法查看扫描仪的输入?
因为我在上面的代码中遇到了问题,如您所见。这是输入错误数据后控制台窗口的输出。而不是我输入KKK的数字,所以有人可以向我解释为什么我两次收到此错误消息吗?

"this is the console"
Customer Type? (C/R) R
Enter Subtotal: KKK
Hay! Entry error please enter a valid number
Enter Subtotal: Hay! Entry error please enter a valid number
Enter Subtotal:

最佳答案

问题是您正在调用scanner.nextdouble(),如果输入中有双精度字,它将正常工作。当输入中没有双精度数时,对nextDouble()的调用将忽​​略输入为“ KKK”的输入,并显示错误消息,然后当您调用nextLine()时,相同的输入“ KKK”仍然在那里等待您会循环返回“ KKK”,然后再将其传递回程序,由于它仍然不是两倍,因此您会收到重复的错误消息。

尝试这个:

    boolean isValid = false;
    Scanner myScanner = new Scanner(System.in).useDelimiter("\\n");
    String customerType = null;
    System.out.print("Customer Type? (C/R) ");
    customerType = myScanner.next();
    while (!isValid)
    {
        System.out.print("Enter Subtotal: ");

        if (myScanner.hasNextDouble())
        {
            double sobTotal = myScanner.nextDouble();
            isValid = true;
        }
        else
        {
            System.out.println("Hay! Entry error please enter a valid number");

            if(myScanner.hasNext()){
              myScanner.next();
            }
        }
    }


这将消耗“ KKK”的无效输入,并使程序正常继续。

10-04 17:54