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.
parseInt will throw NumberFormatException if it cannot parse the integer. So doing this will answer your question
It would be something like this.
You can use a scanner instead of try-catch:
You could try
It is part of
org/apache/commons/lang3/math/NumberUtils
and it checks whether the string can be parsed byInteger.parseInt(String)
,Long.parseLong(String)
,Float.parseFloat(String)
orDouble.parseDouble(String)
.See below:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-
Check if it is integer parseable
or use Scanner
or use Regular Expression like
instead of
try
ing &catch
ing expressions.. its better to run regex on the string to ensure that it is a valid number..