How to check if a string is a valid number in Java

4 Answers

0 votes
public class MyClass {
    public static boolean isNumeric(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
 
        return str.chars().allMatch(Character::isDigit);
    }
 
    public static void main(String[] args)
    {
        String str = "8746";
        
        System.out.println(isNumeric(str));
    }
}




/*
run:

true

*/

 



answered Mar 21, 2023 by avibootz
0 votes
public class MyClass {
    public static boolean isNumeric(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
 
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch < '0' || ch > '9') {
                return false;
            }
        }
        return true;
    }
 
    public static void main(String[] args)
    {
        String str = "8746";
        
        System.out.println(isNumeric(str));
    }
}




/*
run:

true

*/

 



answered Mar 21, 2023 by avibootz
0 votes
public class MyClass {
    public static boolean isNumeric(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
 
        return str.matches("[0-9]+");
    }
 
    public static void main(String[] args)
    {
        String str = "8746";
        
        System.out.println(isNumeric(str));
    }
}




/*
run:

true

*/

 



answered Mar 21, 2023 by avibootz
0 votes
public class MyClass {
    public static boolean isNumeric(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
 
        try {
            Integer.parseInt(str);
        } catch (NumberFormatException ex) {
            return false;
        }
        
        return true;
    }
 
    public static void main(String[] args)
    {
        String str = "8746";
        
        System.out.println(isNumeric(str));
    }
}




/*
run:

true

*/

 



answered Mar 21, 2023 by avibootz

Related questions

1 answer 158 views
1 answer 200 views
1 answer 185 views
1 answer 163 views
1 answer 157 views
2 answers 228 views
...