[java] How to check if a string is numeric?

I have a gpa program, and it works with the equalsIgnoreCase() method which compares two strings, the letter "a" to the user input, which checks if they put "a" or not. But now I want to add an exception with an error message that executes when a number is the input. I want the program to realize that the integer input is not the same as string and give an error message. Which methods can I use to compare a type String variable to input of type int, and throw exception?

This question is related to java

The answer is


I wrote this little method lastly in my program so I can check if a string is numeric or at least every single char is a number.

private boolean isNumber(String text){
    if(text != null || !text.equals("")) {
        char[] characters = text.toCharArray();
        for (int i = 0; i < text.length(); i++) {
            if (characters[i] < 48 || characters[i] > 57)
                return false;
        }
    }
    return true;
}

Here's how to check if the input contains a digit:

if (input.matches(".*\\d.*")) {
    // there's a digit somewhere in the input string 
}

You can use Character.isDigit(char ch) method or you can also use regular expression.

Below is the snippet:

public class CheckDigit {

private static Scanner input;

public static void main(String[] args) {

    System.out.print("Enter a String:");
    input = new Scanner(System.in);
    String str = input.nextLine();

    if (CheckString(str)) {
        System.out.println(str + " is numeric");
    } else {
        System.out.println(str +" is not numeric");
    }
}

public static boolean CheckString(String str) {
    for (char c : str.toCharArray()) {
        if (!Character.isDigit(c))
            return false;
    }
    return true;
}

}


Simple method:

public boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}


public boolean isOnlyNumber(String value) {
    boolean ret = false;
    if (!isBlank(value)) {
        ret = value.matches("^[0-9]+$");
    }
    return ret;
}

Use this

public static boolean isNum(String strNum) {
    boolean ret = true;
    try {

        Double.parseDouble(strNum);

    }catch (NumberFormatException e) {
        ret = false;
    }
    return ret;
}

Many options explored at http://www.coderanch.com/t/405258/java/java/String-IsNumeric

One more is

public boolean isNumeric(String s) {  
    return s != null && s.matches("[-+]?\\d*\\.?\\d+");  
}  

Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.


To check for all int chars, you can simply use a double negative. if (!searchString.matches("[^0-9]+$")) ...

[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.


Use below method,

public static boolean isNumeric(String str)  
{  
  try  
  {  
    double d = Double.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;  
}

If you want to use regular expression you can use as below,

public static boolean isNumeric(String str)
{
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}


If you are allowed to use third party libraries, suggest the following.

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

NumberUtils.isDigits(str:String):boolean
NumberUtils.isNumber(str:String):boolean

public static boolean isNumeric(String string) {
    if (string == null || string.isEmpty()) {
        return false;
    }
    int i = 0;
    int stringLength = string.length();
    if (string.charAt(0) == '-') {
        if (stringLength > 1) {
            i++;
        } else {
            return false;
        }
    }
    if (!Character.isDigit(string.charAt(i))
            || !Character.isDigit(string.charAt(stringLength - 1))) {
        return false;
    }
    i++;
    stringLength--;
    if (i >= stringLength) {
        return true;
    }
    for (; i < stringLength; i++) {
        if (!Character.isDigit(string.charAt(i))
                && string.charAt(i) != '.') {
            return false;
        }
    }
    return true;
}