Friday 18 October 2019

Java - If String is Integer without causing an Exception.

I hade some issues finding a way to check a value for Integer and didn't want to have an exception thrown. I found the following solution suitable at the time.
String input = "something";
boolean numeric = true;

try {
    Integer num = Integer.parseInt(input);
    } catch (NumberFormatException e) {
        numeric = false;
        }

    if(numeric) {
        System.out.println(input + " is a number");
        } else {
            showError(input, "not a number");
        }
//In this case the result would be sent to the showError() method. Instead of throwing an exception.
Share:

0 comments:

Post a Comment

Search