我正在创建一个 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-catch
try {
choiceofcake = Integer.parseInt(userinput);
if (choiceofcake > 5 || choiceofcake < 1) {
break;
}
} catch (NumberFormatException ee) {
ee.printStatckTrace ();
continue;
}
关于java - 如何在我的代码中添加 try 、 catch 语句以仅接受整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54510789/