如何在Kotlin中将String转换为Int? [英] How to convert String to Int in Kotlin?
本文介绍了如何在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.
我该如何解决?
推荐答案
您可以在String
实例上调用toInt()
:
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屋!
查看全文