The error you're likely getting is a NumberFormatException. This is because ("" != [0-9]+) && value value !< Int.MAX_VALUE && !> Int.MIN_VALUE.
You have three options:
- Check if it's empty first, as sandip mentioned.
- Use
toIntOrNull
- Catch the exception.
toInt
throws an exception (NumberFormatException) if the int is invalid. This means:
- Not a number with the defined radix (default 10; an actual int. I.e. 16 is hex, but it's not applicable here)
- The number is too big or too small (under Int.MIN_VALUE or over Int.MAX_VALUE).
- The String is empty.
Checking if it's empty first solves half the problem; it can't be valid if it's empty. However, it doesn't solve it if there are letters or the number is too big.
You can use toIntOrNull()
for this. It's just like toInt()
, but it returns null if the conversion fails. You can use the elvis operator with a run block, or just use a simple if-statement to check if it's null, and handle the problems accordingly.
val num1: Int = ednum1.text.toString().toIntOrNull() ?: run {
// Notify the user the first number is invalid
return; // return from the method to avoid NPE's
}
val num2: Int = ednum2.text.toString().toIntOrNull() ?: run {
// Notify the user the second number is invalid
return;
}
if you don't understand what run
does here, take a look at this question. You can also get rid of run
entirely and assign a number value, just let it be null and handle it later, or something else.
The max positive value of an int is about 2.4 billion. If you expect numbers with a higher input than that, use Long
, and equivalently toLongOrNull()
.
The last option is catching the error.
var num1: Int? = try { ednum1.text.toString().toInt() } catch (e: NumberFormatException) {
// You can do a lot of stuff in here; you can notify the user and `return` from the method,
// set it to null and handle it later, or assign an integer value.
null
}
var num2: Int? = try { ednum2.text.toString().toInt() } catch (e: NumberFormatException) {
// see my comments on the first block; same applies here
null
}
It is, in my opinion, slightly more bulky than toIntOrNull()
( / toLongOrNull()
), but it is an option.