Java - checking if parseInt throws exception

146,830

Solution 1

public static boolean isParsable(String input) {
    try {
        Integer.parseInt(input);
        return true;
    } catch (final NumberFormatException e) {
        return false;
    }
}

Solution 2

Check if it is integer parseable

public boolean isInteger(String string) {
    try {
        Integer.valueOf(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

or use Scanner

Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");

while (scanner.hasNext()) {
    if (scanner.hasNextDouble()) {
        Double doubleValue = scanner.nextDouble();
    } else {
        String stringValue = scanner.next();
    }
}

or use Regular Expression like

private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");

public boolean isDouble(String string) {
    return doublePattern.matcher(string).matches();
}

Solution 3

It would be something like this.

String text = textArea.getText();
Scanner reader = new Scanner(text).useDelimiter("\n");
while(reader.hasNext())
    String line = reader.next();

    try{
        Integer.parseInt(line);
        //it worked
    }
    catch(NumberFormatException e){
       //it failed
    }
}

Solution 4

parseInt will throw NumberFormatException if it cannot parse the integer. So doing this will answer your question

try{
Integer.parseInt(....)
}catch(NumberFormatException e){
//couldn't parse
}

Solution 5

You can use a scanner instead of try-catch:

Scanner scanner = new Scanner(line).useDelimiter("\n");
if(scanner.hasNextInt()){
    System.out.println("yes, it's an int");
}
Share:
146,830
Mike Haye
Author by

Mike Haye

Updated on May 14, 2020

Comments

  • Mike Haye
    Mike Haye almost 4 years

    I'm wondering how to do something only if Integer.parseInt(whatever) doesn't fail.

    More specifically I have a jTextArea of user specified values seperated by line breaks.

    I want to check each line to see if can be converted to an int.

    Figured something like this, but it doesn't work:

    for(int i = 0; i < worlds.jTextArea1.getLineCount(); i++){
                        if(Integer.parseInt(worlds.jTextArea1.getText(worlds.jTextArea1.getLineStartOffset(i),worlds.jTextArea1.getLineEndOffset(i)) != (null))){}
     }
    

    Any help appreciated.

  • Amir Raminfar
    Amir Raminfar almost 13 years
    Don't catch ALL exceptions. That's really bad practice.
  • josh.trow
    josh.trow almost 13 years
    Why the downvote? This is a valid answer, and though the Exception catching is too vague for good practice it will work.
  • Yet Another Geek
    Yet Another Geek almost 13 years
    @josh.trow, throwing an exception when doing a parseint is also bad practice as it really is not something truly exceptional, one could either provide a parsable method (to check if it can be parsed) or convert it to a weird value (like Ruby and perl)
  • user207421
    user207421 almost 13 years
    NumberFormatException. You may as well get it right. It's documented.
  • user207421
    user207421 almost 13 years
    So what is the exception for?
  • user207421
    user207421 almost 13 years
    Better how? Why reinvent the wheel? Why run the risk that the regex doesn't match what parseInt() does? Why waste the time and the money?
  • Anantha Sharma
    Anantha Sharma almost 13 years
    when an exception there is an overhead (for the JVM) to prepare the stack trace & then continue with executing the program (this is a bit time consuming)... its always better to check the expression before parsing it..
  • user207421
    user207421 almost 13 years
    The overhead is insignificant, and the other issues I raised are not. Your blanket statement is not supportable.
  • Pascal Kesseli
    Pascal Kesseli about 10 years
    +1 for verification without exceptions using Scanner.
  • Admin
    Admin over 7 years
    this will ONLY work with this specific try/catch statement or any other NumberFormatException.
  • Luís Henriques
    Luís Henriques almost 6 years
    This should be the correct answer, as the accepted one is wrong.
  • Adam
    Adam over 5 years
    7 years later and no-one has picked up on this one - accusations of 'blanket statements' is not helpful. If performance is critical, then it would be necessary to run comparisons of the two techniques. Neither preparing regex nor stacktraces are completely negligible. And in fact the regex could be cached.
  • Kerem Baydoğan
    Kerem Baydoğan over 5 years
    "Don't catch ALL exceptions. That's really bad practice." In this case, it is perfectly fine and also the right thing to do because what you are only doing is checking if anything went wrong. Catch all exceptions and log them.
  • DownloadPizza
    DownloadPizza almost 4 years
    Catching ALL exceptions is never the right thing to do, as the only Exceptions which are expected here are the ones thrown by parseInt. If anything else were to go wrong you would not want the program to keep running (lets say an illegalaccessexception because someone messed with reflection)