如果用户输入字符串而不是 Int (JOptionPane),如何捕获错误

How to catch an error if user inputs a String instead of 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,如果他键入字符串,他将收到错误消息并再次弹出 window 年龄。

我尝试了所有方法来捕捉错误,但我总是失败。我无法使用 age=Integer.parseInt(age).hasNextInt 或其他类似的东西来完成此操作。他们总是给我一个错误。

我看了很多关于如何使用普通扫描仪和 system.println 的教程,但我无法弄清楚 JOptionPane 的分辨率。

我试过 try/catch,但我不明白,而且从来没有用过。

你能帮帮我吗?我是 Java 的新人,如有任何帮助,我将不胜感激。

编辑:我修好了!非常感谢 Andrew 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));
    }

使用 try/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

Java内置函数:

public static boolean isNumeric(String str){
for (int i = str.length();--i>=0;){ 
    if (!Character.isDigit(str.charAt(i))){
        return false;
    }
}
return true;

}

正则表达式,最快:

public static boolean isInteger(String str) { 
    Pattern pattern = Pattern.compile("^[-\+]?[\d]*$"); 
    return pattern.matcher(str).matches(); 

}

使用ascii码:

    public static boolean isNumeric(String str){
    for(int i=str.length();--i>=0;){
        int chr=str.charAt(i);
        if(chr<48 || chr>57)
            return false;
    }
   return true;
}