IntelliJ IDEA: Why is readLine() expecting two user inputs instead of one using Kotlin?

荒凉一梦 提交于 2021-01-07 02:57:27

问题


I wrote a simple program that takes the user's input from the console and then prints it. But when the user enters the input, it requests a second user input and only reads the second input.

Code:

fun main(args: Array<String>) {
    print("Enter text: ")
    val stringInput = readLine()!!
    println("Readed text: $stringInput")
}

Console:

> Task :MainKt.main()
Enter text: FirstInput
SecondInput
Disconnected from the target VM, address: 'localhost:37282', transport: 'socket'
Connected to the target VM, address: '127.0.0.1:37264', transport: 'socket'
Readed text: SecondInput

I'm using the latest version of IntelliJ IDEA. I don't know why this is happening. I'm using Windows.


回答1:


This seems to be a bug in IntelliJ's internal console: see this ticket (found via this answer).

(The same issue also appears to be behind this question and this question.)

I don't know if it refers to the same problem, but this answer recommends changing the JRE options in the Edit Configurations menu, and then changing them back again.




回答2:


It might be because you are using "!!". Double bang (!!) or double exclamation operator or not-null assertion operator is used with variables that you are sure the value will be always be asserted (not null). If a value is null and one uses "!!", a one null pointer exception will be thrown. So, this operator is only used if we want to throw one exception always if any null value is found.

In your case:

fun main(args: Array<String>) {
    print("Enter text: ")

    val stringInput = readLine()
    println("Readed text: $stringInput")
}

You would want to use !! for example:

fun main(args: Array) {
   println("Enter text: ")
   val stringInput = null

   val inputLength = stringInput!!.length

   println("Length of the string is : $inputLength")

}

Since user input is null, the length of string would be null, hence The program will throw one kotlin.KotlinNullPointerException



来源:https://stackoverflow.com/questions/65281189/intellij-idea-why-is-readline-expecting-two-user-inputs-instead-of-one-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!