我创建了一个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);

最佳答案

包好

choiceofcake = Integer.parseInt(userinput);


尝试捕捉

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

08-03 17:58