Home > front end >  How to use a while loop to keep looping until condition met with user input kotlin
How to use a while loop to keep looping until condition met with user input kotlin

Time:10-06

Using a while loop to keep looping until condition is met.

When pin correct: Displays no message, exits program.

When user inputs wrong pin: Displays correct error message Pin is incorrect, Keeps promting user for input and keeps displaying Pin is incorrect.

When user inputs a non integer data type: Displays correct error message Pin is incorrect, Keeps promting user for input and keeps displaying Pin is incorrect.

Here is my code

fun main() {
    println("Create PIN: ")
    val pin = readln().toIntOrNull()

    println("Enter PIN: ")
    val input = readln().toIntOrNull()

    while (input != pin) {
        if (input == pin) {
            println("PIN is correct")
        }
        else{
            println("Pin is incorrect")
            readln().toIntOrNull()
        }
    }
}

EDIT: I needed to walk away, was feeling like smashing my head against my keyboard haha. Ended up getting it working.

Here's the fix

fun main() {
println("Create PIN: ")
val pin = readln().toIntOrNull()

println("Enter PIN: ")
var input = readln().toIntOrNull()

while (input != pin)
{
    println("PIN is incorrect")
    input = readln().toIntOrNull()
}
if (input == pin){
    println("PIN is correct")
}

}

CodePudding user response:

You forgot to capture newly typed pin. And since you are changing value of the variable you need to use var instead of val

var input = readln().toIntOrNull()

instead of

    else{
        println("Pin is incorrect")
        readln().toIntOrNull()
    }

use

else{
        println("Pin is incorrect")
        input = readln().toIntOrNull()
    }

CodePudding user response:

I know you already solved it, but just want to share an alternate design pattern you could use in this situation. A while(true) loop keeps running until you call break inside it. It can lead to less code repetition in cases like what you're doing here.

Notice you only have to use readln().toIntOrNull() once instead of twice, and the input variable becomes unnecessary:

fun main() {
    println("Create PIN: ")
    val pin = readln().toIntOrNull()

    println("Enter PIN: ")
    while (true) {
        if (readln().toIntOrNull() == pin) {
            println("PIN is correct")
            break
        }
        println("PIN is incorrect")
    }
}
  • Related