首页 > 解决方案 > Kotlin readLine 在基本程序中给出错误,其中输入来自用户,并且显示为输出

问题描述

以下代码:

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 编译器中尝试过同样的方法,但我得到了同样的错误。

标签: kotlinreadline

解决方案


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

例如,在https://ideone.com/上,您可以说出要使用什么输入,它会打印该行(尽管它的 Kotlin 版本已经很老了)。


推荐阅读