首页 > 解决方案 > 如何在我的代码中添加 try 、 catch 语句以仅接收整数值?

问题描述

我创建了一个 JOptionPane 对话框来接受用户的输入以选择他们想要购买的蛋糕类型,但我只想接受一个整数值。我对 java 编程很陌生,需要一些帮助,使用 try, catch 只获取一个整数值。

我创建了“Cakes[]”数组来存储和检索蛋糕的味道、蛋糕的价格和剩余的蛋糕数量。

do {

    do {
        String userinput = JOptionPane.showInputDialog(null, "Enter your choice of cake:"
        + "\n" + "1." + Cakes[0].getflavorofcake() + "(" + Cakes[0].getpriceofcake() + "cents" + ")" + "    no. of cakes available:" + Cakes[0].getnofcaksleft()
        + "\n" + "2." + Cakes[1].getflavorofcake() + "(" + Cakes[1].getpriceofcake() + "cents" + ")" + "      no. of cakes available:" + Cakes[1].getnofcaksleft()
        + "\n" + "3." + Cakes[2].getflavorofcake() + "(" + Cakes[2].getpriceofcake() + "cents" + ")" + "            no. of cakes available:" + Cakes[2].getnofcaksleft()
        + "\n" + "4." + Cakes[3].getflavorofcake() + "(" + Cakes[3].getpriceofcake() + "cents" + ")" + "        no. of cakes available:" + Cakes[3].getnofcaksleft()
        + "\n" + "5." + Cakes[4].getflavorofcake() + "(" + Cakes[4].getpriceofcake() + "cents" + ")" + "          no. of cakes available:" + Cakes[4].getnofcaksleft(), "mini cake shop", JOptionPane.QUESTION_MESSAGE);

        choiceofcake = Integer.parseInt(userinput);

        showthatthereisnocakesleft(choiceofcake);//Method called to show user that the choiceofcake chosen is no longer available

    } while (Cakes[choiceofcake - 1].getnofcaksleft() < 1);

    if (choiceofcake > 5 || choiceofcake < 1) {
    JOptionPane.showMessageDialog(null, "Invalid input! Please enter in the range from  1 to 5", "Error", JOptionPane.ERROR_MESSAGE);
    }
} while (choiceofcake > 5 || choiceofcake < 1);

标签: java

解决方案


包裹

choiceofcake = Integer.parseInt(userinput);

尝试捕捉

try {
   choiceofcake = Integer.parseInt(userinput);
   if (choiceofcake > 5 || choiceofcake < 1) {
        break;
   }
} catch (NumberFormatException ee) {
    ee.printStatckTrace ();
    continue;
}

推荐阅读