Reputation: 1632
I am working on a console application in Kotlin where I accept multiple arguments in main()
function
fun main(args: Array<String>) {
// validation & String to Integer conversion
}
I want to check whether the String
is a valid integer and convert the same or else I have to throw some exception.
How can I resolve this?
Upvotes: 124
Views: 196851
Reputation: 81
If you actually have a String
, call toInt()
on it:
val myInt = myString.toInt()
Are you actually sure it's a String
, though? If you're iterating over a single String
, you don't get instances of String
of length 1 (as you might expect if you're used to another language, ie, Python), but instances of Char
, in which case you want to use digitToInt()
instead:
val myInt = myChar.digitToInt()
Upvotes: 8
Reputation: 21
You can call toInt()
on a String
to turn it into an Integer.
val number_int = str.toInt()
If it cannot be converted, it will throw a NumberFormatException
error.
You could put it in a try-catch
block:
try {
val strVal = "IamNotanInteger"
val intVal = strVal.toInt()
println(intVal)
} catch (e: NumberFormatException) {
println("This String is not convertible.")
}
toIntOrNull()
will also convert a String
into an Integer
, but it will return null
instead of throwing an error.
fun main() {
val strVal = "246b"
val intVal = strVal.toIntOrNull()
println(intVal) // null
}
Here’s how to use the parseInt() method to convert Kotlin String to Int.
fun main() {
val strVal = "246"
val intVal = Integer.parseInt(strVal)
println(intVal) // 246
}
You can pass a radix into the toInt()
and toIntOrNull()
methods:
fun main() {
val base16String = "3F"
val base16Int = base16String.toInt(16)
// String Interpolation
println("$base16Int") // 63 (If I did the maths correct...)
}
Useful Links
Upvotes: 2
Reputation: 14560
Actually, there are several ways:
Given:
// aString is the string that we want to convert to number
// defaultValue is the backup value (integer) we'll have in case of conversion failed
var aString: String = "aString"
var defaultValue : Int = defaultValue
Then we have:
Operation | Successful operation | Unsuccessful Operation |
---|---|---|
aString.toInt() | Numeric value | NumberFormatException |
aString.toIntOrNull() | Numeric value | null |
aString.toIntOrNull() ?: defaultValue | Numeric value | defaultValue |
If aString
is a valid integer, then we will get is numeric value, else, based on the function used, see a result in column Unsuccessful Operation
.
Upvotes: 39
Reputation: 11
You can Direct Change by using readLine()!!.toInt()
Example:
fun main(){
print("Enter the radius = ")
var r1 = readLine()!!.toInt()
var area = (3.14*r1*r1)
println("Area is $area")
}
Upvotes: 1
Reputation: 1334
In Kotlin:
Simply do that
val abc = try {stringNumber.toInt()}catch (e:Exception){0}
In catch block you can set default value for any case string is not converted to "Int".
Upvotes: 5
Reputation: 28865
As suggested above, use toIntOrNull()
.
Parses the string as an [Int] number and returns the result or
null
if the string is not a valid representation of a number.
val a = "11".toIntOrNull() // 11
val b = "-11".toIntOrNull() // -11
val c = "11.7".toIntOrNull() // null
val d = "11.0".toIntOrNull() // null
val e = "abc".toIntOrNull() // null
val f = null?.toIntOrNull() // null
Upvotes: 7
Reputation: 3645
I use this util function:
fun safeInt(text: String, fallback: Int): Int {
return text.toIntOrNull() ?: fallback
}
Upvotes: 4
Reputation: 1
fun getIntValueFromString(value : String): Int {
var returnValue = ""
value.forEach {
val item = it.toString().toIntOrNull()
if(item is Int){
returnValue += item.toString()
}
}
return returnValue.toInt()
}
Upvotes: 0
Reputation: 13863
val i = "42".toIntOrNull()
Keep in mind that the result is nullable as the name suggests.
Upvotes: 20
Reputation: 19427
You could call toInt()
on your String
instances:
fun main(args: Array<String>) {
for (str in args) {
try {
val parsedInt = str.toInt()
println("The parsed int is $parsedInt")
} catch (nfe: NumberFormatException) {
// not a valid int
}
}
}
Or toIntOrNull()
as an alternative:
for (str in args) {
val parsedInt = str.toIntOrNull()
if (parsedInt != null) {
println("The parsed int is $parsedInt")
} else {
// not a valid int
}
}
If you don't care about the invalid values, then you could combine toIntOrNull()
with the safe call operator and a scope function, for example:
for (str in args) {
str.toIntOrNull()?.let {
println("The parsed int is $it")
}
}
Upvotes: 139
Reputation: 17849
i would go with something like this.
import java.util.*
fun String?.asOptionalInt() = Optional.ofNullable(this).map { it.toIntOrNull() }
fun main(args: Array<String>) {
val intArgs = args.map {
it.asOptionalInt().orElseThrow {
IllegalArgumentException("cannot parse to int $it")
}
}
println(intArgs)
}
this is quite a nice way to do this, without introducing unsafe nullable values.
Upvotes: 2