Using an if statement to test if JTextField is an integer

后端 未结 3 1648
栀梦
栀梦 2021-01-28 02:07

I want my program to be able to tell if what is inside my two JTextFields is an integer or a String.

CODE

          public void actionP         


        
3条回答
  •  时光说笑
    2021-01-28 02:41

    Not sure exactly where in your code the test is being performed, but you can use this method to determine if a String is an integer:

    public static boolean isInteger(String s) {
        try { 
            Integer.parseInt(s); 
        } catch(NumberFormatException e) { 
            return false; 
        }
        // if exception isn't thrown, then it is an integer
        return true;
    }
    

    Less expensive none exception based way, assuming your code does not need to throw an exception:

    public static boolean isInt(String s){
            for(int i = 0; i < s.length(); i++){
                if(!Character.isDigit(s.charAt(i))){
                     return false;
                }
            }
            return true;
    }
    

提交回复
热议问题