如何在 Kotlin 中将 String 转换为 Int?

如何在 Kotlin 中将 String 转换为 Int?

问题描述:

我正在 Kotlin 中开发一个控制台应用程序,我在 main() 函数中接受多个参数

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
}

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

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?

你可以在你的 String 实例上调用 toInt() :

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
        }
    }
}

或者 toIntOrNull() 作为替代:

for (str in args) {
    val parsedInt = str.toIntOrNull()
    if (parsedInt != null) {
        println("The parsed int is $parsedInt")
    } else {
        // not a valid int
    }
}

如果您不关心无效值,那么您可以将 toIntOrNull() 与安全调用运算符和作用域函数结合起来,例如:

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