44

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
user1944277
  • 465
  • 1
  • 4
  • 4

11 Answers11

67

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.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • 2
    I would change the last "+" to a "*" so that `123.` becomes valid input (nothing after decimal delimiter is valid input) – peterh Dec 03 '15 at 05:33
  • 3
    I would add a check for NULL ... otherwise it will crash – Stefan Michev Apr 26 '17 at 08:11
  • @StefanMichev people should stop passing null arguments. It's not right for every method in the world to have a null, empty or whatever check. – Buffalo Jun 07 '18 at 07:31
  • This is easy code but millions of Java programmers have to write it. It should be in that standard library. – Yetti99 Apr 08 '19 at 16:04
34

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
kachingy123
  • 197
  • 1
  • 12
Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
8

Use this

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

        Double.parseDouble(strNum);

    }catch (NumberFormatException e) {
        ret = false;
    }
    return ret;
}
NPKR
  • 5,368
  • 4
  • 31
  • 48
6

You can also use ApacheCommons StringUtils.isNumeric - http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isNumeric(java.lang.String)

Rudi
  • 419
  • 6
  • 10
  • I didn't vote you down, but you don't need to add more software. In Java SE: loop: if(Character.isDigit(c)) – Roger F. Gay Apr 12 '15 at 13:52
  • 2
    Beware! isNumeric only tackles pure numbers. i.e., it will return false for 7,574. (comma-separated numbers). – Kashif Nazar Dec 03 '15 at 07:20
  • Why does it return true for question marks? https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNumeric(java.lang.CharSequence) – pete Jul 14 '16 at 22:13
6

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;
}
Alberto Cerqueira
  • 1,339
  • 14
  • 18
5

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.
}
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
  • 1
    Try-and catching an excpetion has such a huge overhead though. – WorldSEnder Oct 05 '15 at 02:14
  • Coding by exception is a known anti-pattern. See https://en.wikipedia.org/wiki/Coding_by_exception and https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why – mcalmeida Jan 26 '18 at 17:11
  • The method of using `Double.parseDouble()` isn't acceptable for internationalized coding situations. It will work reasonably well in the USA, but number strings with valid doubles in other countries will not necessarily parse correctly. For example, in some locales, the thousands separator can be a space " ", and "123 456" will cause a NumberFormatException even though it's a parseable number. – Kenny Wyland Jul 06 '18 at 00:17
3
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;
}
Nadalet
  • 57
  • 1
  • 7
2

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;
}
Georg M.
  • 31
  • 4
1

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

}

0

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

if (input.matches(".*\\d.*")) {
    // there's a digit somewhere in the input string 
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • hey, thanks, this helped, but m program still terminates after the exception throws. if I take out the exception, it runs perfectly...just the way I requested even if theres a number. any idea on how to still keep the prgm running after I thorw the exception – user1944277 Jan 08 '13 at 01:37
  • Wrap the code throwing the ex ration in a try-catch, catching the exception thrown. – Bohemian Jan 08 '13 at 01:49
  • I already tried just wrapping my entirepart of the code which prompts inputs in a try catch, but it didn't work, can u clarify using my posted code above – user1944277 Jan 08 '13 at 02:04
  • What code posted where? I can't see any code. – Bohemian Jan 08 '13 at 04:18
0

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.

Roger F. Gay
  • 1,830
  • 2
  • 20
  • 25