Anonymous Human
Anonymous Human

Reputation: 1948

Safe conversion to integer and then test

I have the user input a value which always comes in as a string. In some cases, I know I will be able to convert it to an integer but not in others. For example

'3' is good but '3A' will not convert to an integer.

In the cases it can convert to an integer, I need to compare its value to another integer so I am trying to do something this like:

if (valueToBeTested.toInteger().getClass == java.lang.Integer 
    && valueToBeTested.toInteger() >= 5) {
// do whatever
}

The only problem is that toInteger() will not return a result when it can't convert something to an integer so how can I safely perform the test in my if condition? I perform the first test to try and see if it successfully converted to an integer, the second test is obvious.

Upvotes: 1

Views: 105

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

if (valueToBeTested.isInteger() && valueToBeTested.toInteger() >= 5 ) { .. }

isNumber() can be used when any number (integer, float, double) is expected.

Upvotes: 4

Related Questions