mxgenius
mxgenius

Reputation: 65

How to break out of a while loop if a blank line or null is entered?

I would like to ask the user for input of "Any" type (strings, ints, double, etc.) and add them to a mutablelist. However I can't seem to find a way to break out the while loop when a blank line or null value is entered. Here's and example of what I'm trying. Thank you.

val someInfo = mutableListOf<Any>()

while (true){
    someInfo.add(readLine()!!)
    //how to break out of this loop when a user enters a blank line or null value?

}

Upvotes: 0

Views: 1746

Answers (2)

Some random IT boy
Some random IT boy

Reputation: 8457

You need to check the result value of readLine() before deciding what to do:

while(true) {
    when(val result = readLine().orEmpty()) {
        // result is an empty string, break out the loop
        "" -> break
        else -> someInfo.add(result)
    }
}

Should do the trick.

The String?.orEmpty() kotlin extension function converts any null value into an empty String so no need to worry to check for null. Still, here you may want to watch out for any exception

Upvotes: 1

cactustictacs
cactustictacs

Reputation: 19534

Simplest way is probably just

while(true) {
    val input = readLine()
    if (input.isNullOrEmpty()) break // or isNullOrBlank (includes empty whitespace)
    // do stuff
}

if you want to do a Kotlin and skip the loops, you could

generateSequence { readLine() }
    .takeWhile { !it.isNullOrEmpty() }
    .forEach { // do a thing }

Upvotes: 1

Related Questions