Java - checking if parseInt throws exception

Mike Haye picture Mike Haye · Jun 23, 2011 · Viewed 133.7k times · Source

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.

Answer

fmucar picture fmucar · Jun 23, 2011
public static boolean isParsable(String input) {
    try {
        Integer.parseInt(input);
        return true;
    } catch (final NumberFormatException e) {
        return false;
    }
}