Reputation: 51
EDIT: ANSWER TO THIS IS BELOW
Really new to kotlin, wanting to check if user entered an Integer, using if else statement. Need to add a do while loop to it later.
Expecting Error Message: Incorrect
When I hover over (input != pin) it displays Condition 'input != pin' is always true.
Here's my code
fun main() {
println("Create PIN: ")
val pin = readln().toInt()
println("Enter PIN: ")
val input = readln().toInt()
if (input == pin){
println ("Correct")
}
else if (input != pin) {
println("Incorrect")
}
}
Upvotes: 1
Views: 928
Reputation: 2639
Because if input == pin
is false so input != pin
is always true, that's why you don't need the second else if you can just replace it with if:
fun main() {
println("Create PIN: ")
val pin = readln().toInt()
println("Enter PIN: ")
val input = readln().toInt()
if (input == pin){
println ("Correct")
}
else {
println("Incorrect")
}
}
But now if the user enters something that can't be converted to int ( some characters for example "hello"... ) .toInt() is going to throw a NumberFormatException
and your code is not going to work so to fix that problem and handle the case when a user enters something other that Int
, you can use .toIntOrNull()
instead of .toInt()
.
.toIntOrNull()
: Parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.
So if pin or input is null, that mean that the user enters something that can't be converted to Int.
fun main() {
println("Create PIN: ")
val pin = readln().toIntOrNull()
println("Enter PIN: ")
val input = readln().toIntOrNull()
if (input == null || pin == null) {
println("PIN is not valid")
}
else if (input == pin){
println ("Correct")
}
else {
println("Incorrect")
}
}
Upvotes: 3