Home > Blockchain >  Read one or two variables alternately in one line
Read one or two variables alternately in one line

Time:01-03

I have declared 2 variables to read from console but on other case i want to read just one of them but i can't.

My code:

print("Enter two numbers in format: {source base} {target base} (To quit type /exit) ")
val (sourceBase, targetBase) = readLine()!!.split(" ")

`I can't type /exit because i've got IndexOutOfBoundsException.

Any tips?

Edit: Thank you all for respond, especially lukas.j, it's working now.

CodePudding user response:

Add a second element, an empty string, if the splitted readLine() contains less than 2 elements:

val (sourceBase, targetBase) = readLine()!!.split(" ").let { if (it.size < 2) it   "" else it }
  • Related