哪个更好?Integer.valueOf(readLine()) 或 readLine()!.toInt()

Which is better? Integer.valueOf(readLine()) or readLine()!!.toInt()

提问人:G Sekyere 提问时间:9/21/2023 更新时间:9/21/2023 访问量:29

问:

我正在使用 codeacademy 学习 Kotlin。在 Madlibs 项目中,我被要求使用 readLine() 从用户那里读取数字输入,然后将其转换为整数。我想知道这两种解决方案中哪一种更好。

这是我的解决方案:distance = readLine()!!.toInt()

这是给定的解决方案:distance = Integer.valueOf(readLine())

字符串 Kotlin 输入 整数 读取行

评论

1赞 Slaw 9/21/2023
另外,请考虑使用 readln() 而不是 .前者返回,而后者返回。readLine()StringString?

答:

1赞 Jorn 9/21/2023 #1

toInt()是更好的解决方案。它位于 Kotlin 标准库和 Java 库中。始终首选仅限 Kotlin 的解决方案,而不是可用的 Java 解决方案。Integer.parseInt