39

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.

2

8 Answers 8

62
public static boolean isParsable(String input) {
    try {
        Integer.parseInt(input);
        return true;
    } catch (final NumberFormatException e) {
        return false;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Don't catch ALL exceptions. That's really bad practice.
NumberFormatException. You may as well get it right. It's documented.
this will ONLY work with this specific try/catch statement or any other NumberFormatException.
"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.
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)
28

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

1 Comment

+1 for verification without exceptions using Scanner.
12

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

Comments

10

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
}

1 Comment

This should be the correct answer, as the accepted one is wrong.
8

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

Comments

3

You could try

NumberUtils.isParsable(yourInput)

It is part of org/apache/commons/lang3/math/NumberUtils and it checks whether the string can be parsed by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String).

See below:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-

Comments

2

You can use the try..catch statement in java, to capture an exception that may arise from Integer.parseInt().

Example:

try {
  int i = Integer.parseint(stringToParse);
  //parseInt succeded
} catch(Exception e)
{
   //parseInt failed
}

3 Comments

Why the downvote? This is a valid answer, and though the Exception catching is too vague for good practice it will work.
@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)
So what is the exception for?
2

instead of trying & catching expressions.. its better to run regex on the string to ensure that it is a valid number..

4 Comments

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?
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..
The overhead is insignificant, and the other issues I raised are not. Your blanket statement is not supportable.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.