java - 如果用户输入 String 而不是 Int (JOptionPane),如何捕获错误
问题描述
int [] numbers = {1,2,3,4};
Random random = new Random();
int totalGood=0;
int totalFalse=0;
String titl = "title1";
String titl2 = "Question";
String titl3 = "Error!";
boolean ages = true;
String name = JOptionPane.showInputDialog(null,"Welcome Please enter your name:",titl,JOptionPane.PLAIN_MESSAGE,new ImageIcon(image0), null,"").toString();
while(ages == true){
int age = Integer.parseInt(JOptionPane.showInputDialog(null,"Welcome" + " " + name +"!" + " " + "How old are you?",titl2,3));
if(age <=28){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:" + " " +age,titl,2));
}else if(age >=29 && age <=40){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:"+ " "+age,titl,2));
}else if(age>=41){
JOptionPane.showMessageDialog(null,String.format("Text " + " " + "Your age:" + " "+age,titl,2));
}else{
// the part where I get stuck!
// What to write here to catch an error and return the user to again input int age if he types String instead?
continue;
}
}
我正在尝试验证用户输入以仅允许 Int 并且如果他键入一个字符串,他将收到一个错误,并且会再次弹出一个年龄窗口。
我尝试了一切来捕捉错误,但我一直在失败。我无法用age=Integer.parseInt(age)
or.hasNextInt
或其他类似的东西来实现这一点。他们总是给我一个错误。
我看到了很多关于如何使用普通 Scanner 和 的教程system.println
,但我无法弄清楚 JOptionPane 的分辨率。
我试过尝试/捕捉,但我不明白,它永远不会奏效。
你能帮我么?我是 Java 新手,我将不胜感激。
编辑:我修好了!非常感谢安德鲁 Vershinin!
while(ages == true){
Pattern AGE = Pattern.compile("[1-9][0-9]*");
String ageInput = JOptionPane.showInputDialog(null,"Welcome" + " " + name +"!" + " " + "How old are you?",titl2,3);
if(!AGE.matcher(ageInput).matches()){
JOptionPane.showMessageDialog(null,String.format("Please enter only numbers! :)"));
continue;
}
int age = Integer.parseInt(ageInput);
if(age <=28){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:" + " " +age,titl,2));
}else if(age >=29 && age <=40){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:"+ " "+age,titl,2));
}else if(age>=41){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:" + " "+age,titl,2));
}
解决方案
Usingtry/catch
是一种有效的方法,但我建议使用正则表达式,通过一个java.util.regex.Pattern
实例表示:Pattern AGE = Pattern.compile("[1-9][0-9]*");
,它可以翻译为“从 1 到 9 的数字,后跟任意数量的任意数字”,因此它不能为零,并且不能包含前导零。
像这样使用它:
String ageInput = JOptionPane.showInputDialog(null,
"Welcome" + " " + name +"!" + " " + "How old are you?",titl2,3)
if (!AGE.matcher(ageInput).matches()) {
// handle invalid input
}
int age = Integer.parseInt(ageInput); // no exception there
推荐阅读
- flutter - 使用图像包将图像拆分/划分为 6 块
- c - 一般来说,如何防止C语言中发生整数溢出?
- hybris - SAP 物料集成中冗余产品数据的处理
- azure - Azure 数据工厂,将 REST GET 响应传递给 Azure SQL 数据库中的存储过程
- c++ - 完成构建项目“Error.vcxproj”——失败
- python - 在mnist中重新缩放图像
- python - Plotly:躲避散点图分类轴上的重叠点
- python - Instapy“无效的类似元素!”
- ios - Firebase 能源影响
- ios - NotificationServiceExtension 是否适用于本地通知?