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条回答
Deceive 欺骗
2楼-- · 2019-01-15 05:45

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
}
查看更多
干净又极端
3楼-- · 2019-01-15 05:46

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
    }
}
查看更多
Emotional °昔
4楼-- · 2019-01-15 05:51

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");
}
查看更多
干净又极端
5楼-- · 2019-01-15 05:52

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-

查看更多
乱世女痞
6楼-- · 2019-01-15 05:59

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();
}
查看更多
可以哭但决不认输i
7楼-- · 2019-01-15 06:03

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

查看更多
登录 后发表回答