0

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")
}

}

2 Answers 2

1

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")
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like it thank you
0

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()
    }

3 Comments

Vojin not sure what you mean by capture newly typed pin? Thanks for the input.
Like i wrote in the answer. Same thing you did. you were not saving newly entered input from user
Oh I get ya now, was readlining to nothing, but with the edit, readlines to the input?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.