簡體   English   中英

如果用戶輸入 String 而不是 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或其他類似的東西來完成此操作。 他們總是給我一個錯誤。

我看到了很多關於如何使用普通 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));
    }

使用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;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM