How to check if a String is numeric in Java

前端 未结 30 2518
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  后悔当初
    2020-11-21 05:43

    This a simple example for this check:

    public static boolean isNumericString(String input) {
        boolean result = false;
    
        if(input != null && input.length() > 0) {
            char[] charArray = input.toCharArray();
    
            for(char c : charArray) {
                if(c >= '0' && c <= '9') {
                    // it is a digit
                    result = true;
                } else {
                    result = false;
                    break;
                }
            }
        }
    
        return result;
    }
    

提交回复
热议问题