39

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.

Mike Haye
  • 793
  • 3
  • 12
  • 22
  • 6
    just handle `NumberFormatException`. – Bala R Jun 23 '11 at 15:05
  • Possible duplicate of [What is a NumberFormatException and how can I fix it?](http://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it) – xenteros Oct 23 '16 at 12:26

8 Answers8

62
public static boolean isParsable(String input) {
    try {
        Integer.parseInt(input);
        return true;
    } catch (final NumberFormatException e) {
        return false;
    }
}
user2891462
  • 3,033
  • 2
  • 32
  • 60
fmucar
  • 14,361
  • 2
  • 45
  • 50
  • 9
    Don't catch ALL exceptions. That's really bad practice. – Amir Raminfar Jun 23 '11 at 15:07
  • 14
    NumberFormatException. You may as well get it right. It's documented. – user207421 Jun 23 '11 at 23:01
  • 1
    this will ONLY work with this specific try/catch statement or any other NumberFormatException. –  Sep 12 '16 at 04:56
  • 1
    **"Don't catch ALL exceptions. That's really bad practice."** In this case, it is perfectly fine and also the right thing to do because what you are only doing is checking if anything went wrong. Catch all exceptions and log them. – Kerem Baydoğan Jan 24 '19 at 09:21
  • 1
    Catching ALL exceptions is never the right thing to do, as the only Exceptions which are expected here are the ones thrown by parseInt. If anything else were to go wrong you would not want the program to keep running (lets say an illegalaccessexception because someone messed with reflection) – DownloadPizza May 11 '20 at 19:36
28

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();
}
Kerem Baydoğan
  • 10,475
  • 1
  • 43
  • 50
12

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
    }
}
Stefan Bossbaly
  • 6,682
  • 9
  • 53
  • 82
10

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
}
Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
8

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");
}
dogbane
  • 266,786
  • 75
  • 396
  • 414
2

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-

Siddhartha Ghosh
  • 2,988
  • 5
  • 18
  • 25
2

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
}
Yet Another Geek
  • 4,251
  • 1
  • 28
  • 40
  • Why the downvote? This is a valid answer, and though the Exception catching is too vague for good practice it will work. – josh.trow Jun 23 '11 at 15:12
  • 2
    @josh.trow, throwing an exception when doing a parseint is also bad practice as it really is not something truly exceptional, one could either provide a parsable method (to check if it can be parsed) or convert it to a weird value (like Ruby and perl) – Yet Another Geek Jun 23 '11 at 15:14
  • So what is the exception for? – user207421 Jun 23 '11 at 23:01
2

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

Anantha Sharma
  • 9,920
  • 4
  • 33
  • 35
  • Better how? Why reinvent the wheel? Why run the risk that the regex doesn't match what parseInt() does? Why waste the time and the money? – user207421 Jun 23 '11 at 23:03
  • 2
    when an exception there is an overhead (for the JVM) to prepare the stack trace & then continue with executing the program (this is a bit time consuming)... its always better to check the expression before parsing it.. – Anantha Sharma Jun 24 '11 at 00:17
  • 1
    The overhead is insignificant, and the other issues I raised are not. Your blanket statement is not supportable. – user207421 Jun 24 '11 at 01:25
  • 7 years later and no-one has picked up on this one - accusations of 'blanket statements' is not helpful. If performance is critical, then it would be necessary to run comparisons of the two techniques. Neither preparing regex nor stacktraces are completely negligible. And in fact the regex could be cached. – Adam Dec 14 '18 at 10:51