java - 如何在我的代码中添加 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);
解决方案
包裹
choiceofcake = Integer.parseInt(userinput);
尝试捕捉
try {
choiceofcake = Integer.parseInt(userinput);
if (choiceofcake > 5 || choiceofcake < 1) {
break;
}
} catch (NumberFormatException ee) {
ee.printStatckTrace ();
continue;
}
推荐阅读
- rcpp - 无法集成 renjin 的 Rcpp 包
- python - 在 PIL 中将图像的尺寸更改为一半
- google-apps-script - 提交时触发脚本的 Google 表单始终无法正常工作
- c# - 取消从 Angular 到 .NET Core 的长操作
- c++ - std::shared_ptr operator= 更改对象,而不是指针值?
- python - 气流宏未转换为日期
- c# - Windows 窗体:根据列表选择显示唯一面板
- filter - PowerBI_filter IDs 专门包含列中的值
- docker - 是否可以从没有控制文件和系统表空间的单个数据文件中取回我的数据?
- ansible - ansible 中的 Gluster_Volume 模块