Java - checking if parseInt throws exception

后端 未结 8 1236
清歌不尽
清歌不尽 2020-12-06 09:17

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

相关标签:
8条回答
  • 2020-12-06 09:54

    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
    }
    
    0 讨论(0)
  • 2020-12-06 09:54

    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-

    0 讨论(0)
提交回复
热议问题