如何在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")
}
}