Lizzie
Lizzie

Reputation: 78

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

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.

Upvotes: 0

Views: 597

Answers (2)

gidds
gidds

Reputation: 18607

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.

Upvotes: 3

Simon Sultana
Simon Sultana

Reputation: 243

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

Upvotes: -1

Related Questions