如何在 Kotlin 将字符串转换为整数?

我在 Kotlin 的一个控制台应用工作,在那里我接受 ABc0函数中的多个参数

fun main(args: Array<String>) {
// validation & String to Integer conversion
}

我想检查 String是否是一个有效的整数,并转换相同的,否则我必须抛出一些异常。

我该怎么办?

129072 次浏览

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")
}
}
val i = "42".toIntOrNull()

Keep in mind that the result is nullable as the name suggests.

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.

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.

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
fun getIntValueFromString(value : String): Int {
var returnValue = ""
value.forEach {
val item = it.toString().toIntOrNull()
if(item is Int){
returnValue += item.toString()
}


}
return returnValue.toInt()


}

I use this util function:

fun safeInt(text: String, fallback: Int): Int {
return text.toIntOrNull() ?: fallback
}
string_name.toString().toInt()

converts string_name to String and then the resulting String is converted to int.

add (?) before fun toInt()

val number_int = str?.toInt()

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".

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")


}