Java - checking if parseInt throws exception

2019-01-15 05:28发布

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.

8条回答
Fickle 薄情
2楼-- · 2019-01-15 06:05

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
}
查看更多
ら.Afraid
3楼-- · 2019-01-15 06:06
public static boolean isParsable(String input){
    boolean parsable = true;
    try{
        Integer.parseInt(input);
    }catch(ParseException e){
        parsable = false;
    }
    return parsable;
}

keep in mind that I meant ParseException as the proper type of exception for the specific case

查看更多
登录 后发表回答