JAVA-如何确保程序仅以扫描的int继续?

时间:2018-09-27 16:40:55

标签: java loops java.util.scanner do-while

我正在学习用Java编程,并且正在开发披萨订购控制台程序。

我已经使整个程序正常工作,但是我想对其进行愚蠢的测试。我要求在三个地方输入int,但是当我输入一个char或一个字符串时,程序崩溃。

我希望实现的目标:

  • 当用户输入有效数字时,程序将继续-完成
  • 当用户输入一个字符或字符串时,他们会收到一条错误消息,循环将重新开始。

这是我代码中的一个示例:

do {
            correctInput = true;
            System.out.println("Step 1: Look through the menu below and type in the NUMBER of the pizza you want.\n"); 

            pizzaMenu();
            System.out.print("\nType in your pizza number here: ");
            pizzaNumber = pizza.nextInt();
            pizza.nextLine();
            switch (pizzaNumber) {
                case 1:
                    pizzaChoice = "Napoli";
                    pizzaPrice = 50;
                    break;
                case 2:
                    pizzaChoice = "Hawaii";
                    pizzaPrice = 50;
                    break;
                case 3:
                    pizzaChoice = "Quattro Stagioni";
                    pizzaPrice = 60;
                    break;
                case 4:
                    pizzaChoice = "Sicillia";
                    pizzaPrice = 75;
                    break;
                case 5:
                    pizzaChoice = "Turbo";
                    pizzaPrice = 60;
                    break;
                case 6:
                    pizzaChoice = "Jamaica";
                    pizzaPrice = 75;
                    break;
                case 7:
                    pizzaChoice = "Romano";
                    pizzaPrice = 60;
                    break;
                case 8:
                    pizzaChoice = "Vulcano";
                    pizzaPrice = 75;
                    break;
                case 9:
                    pizzaChoice = "Vegetariana";
                    pizzaPrice = 60;
                    break;
                case 10:
                    pizzaChoice = "Salame";
                    pizzaPrice = 60;
                    break;
                default:
                    System.out.println("You've entered a wrong number. Try again");
                    correctInput = false;
                    break;
            }
        } while (!correctInput);

您能帮我指出一个可行的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以从扫描仪中读取一个字符串,然后手动尝试将其转换为所需的数字(IntegerDouble):

String str = scan.next();

if (isNumeric(str))
    System.out.println("Numeric value: " + Double.parseDouble(str));
else
    System.out.println("Not a numeric");

检查给定字符串是否为数字的方法:

private static boolean isNumeric(String str) {
    try {
        Double.parseDouble(str);
        return true;
    } catch(NumberFormatException e) {
        return false;
    }
}