Kotlin readLine 在基本程序中给出错误,其中从用户那里获取输入并将其显示为输出

Kotlin readLine gives error in a basic program where input is taken from user and the same is shown as output

以下代码:

fun main(args: Array<String>) {
print("Write anything here: ")

val enteredString = readLine()
println("You have entered this: $enteredString")

}

在 KotlinPlayground 中出现以下错误:

Write anything here: You have entered this: null

在这里,用户没有机会输入。执行初始打印语句后,编译器不会等待用户提供输入,而是跳到下一个打印语句。 为什么会这样?我在其他几个在线 Kotlin 编译器中也尝试过相同的方法,但我遇到了同样的错误。

没有错误。 readLine 只是 returns null(因为 Kotlin Playground 没有可读取的控制台),并且按预期打印。

例如在 https://ideone.com/ 上,您可以说出要用于输入的内容,它会打印该行(尽管它的 Kotlin 版本很旧)。

因为 Kotlin playground 没有用户输入控制台,这不是错误。对于用户输入,您可以使用 https://ideone.com/ https://www.jdoodle.com/compile-kotlin-online/

我会推荐你​​使用第二个jdoodle。 运行 和读取用户输入的速度要快得多,几乎可以使用最新版本的 Kotlin 和 JRE。

如果你喜欢玩 (运行) 命令行参数那么 jdoodle 对你有好处。