如何在 Kotlin 中将 String 转换为 Int? [英] How to convert String to Int in Kotlin?

查看:149
本文介绍了如何在 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")
    }
}

这篇关于如何在 Kotlin 中将 String 转换为 Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆