[英]Kotlin string split with readLine() method
So I have this Java code: 所以我有这个Java代码:
String values = input.nextLine();
String[] longs = values.split(" ");
Which splits the string input into a string array. 它将字符串输入拆分为字符串数组。
I try it in Kotlin 我在科特林尝试
var input: String? = readLine()
var ints: List<String>? = input.split(" ".toRegex())
and I get an error: "Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of the the type String?" 我收到一个错误:“在类型为String的可为空的接收器上只允许安全(?。)或非null断言(!!。)调用吗?”
I am new to Kotlin and would like some clarity on how to do this. 我是Kotlin的新手,并希望了解如何执行此操作。 Thank you!
谢谢!
If you have a look at readLine()
it reveals that it might return null
: 如果您看一下
readLine()
它表明它可能返回null
:
/**
* Reads a line of input from the standard input stream.
*
* @return the line read or `null` if the input stream is redirected to a file and the end of file has been reached.
*/
public fun readLine(): String? = stdin.readLine()
Therefore it's not safe to call split
on its result, you have to handle the null
case, eg as follows: 因此,对结果调用
split
是不安全的,您必须处理null
情况,例如,如下所示:
val input: String? = readLine()
val ints: List<String>? = input?.split(" ".toRegex())
Other alternatives and further information can be found here . 其他替代方法和更多信息可以在这里找到。
Look, you code is almost right, just missed the !!
看,您的代码几乎是正确的,只是错过了
!!
this ensure that the string should not be empty (it will throw a error). 这样可以确保字符串不能为空(它将引发错误)。 You code should be like this:
您的代码应如下所示:
val input: String? = readLine()
var ints: List<String>? = input!!.split(" ".toRegex())
Note that I just added !!
注意,我刚刚添加了
!!
operator and change var
to val
on line 1, because your input should not be changed (it was given by the user). 运算符,并在第1行将
var
更改为val
,因为您的输入不应更改(由用户指定)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.