How to set a Kotlin while loop stop after 3 times?


How to set a Kotlin while loop stop after 3 times?



I'm new to Kotlin, I want to condition my while loop stop after 3 times, please, help! Also it should ask user to quit game or continue


val randomNumber: String = Random().nextInt(10).toString()
var guess= true
println("Welcome to the Number Guess Game")
println("Please guess number between 1 to 10")


do{
val User=readLine()!!.toString()
if(User==randomNumber){
guess=false
}
else{"Sorry Please Try Again"}

}while(guess)
println("Congratulation You have guessed the right number.")





Here is a link to the Kotlin control flow documentation. Check out the for loop, and the concept of break.
– MoxieBall
Jun 29 at 22:19


break




1 Answer
1



Try this.


var correct = false
var tries = 0

val randomNumber = Random().nextInt(10) + 1
println("Welcome to the number guess game")
println("Please guess a number between 1 to 10")

do {
val input = readLine() ?: break
val guess = input.toIntOrNull()

tries += 1
correct = guess == randomNumber
if (!correct) {
println("Sorry please try again!")
}
} while (!correct && tries < 3)

if (correct) {
println("Congratulation You have guessed the right number.")
} else {
println("Sorry. The answer was $randomNumber")
}



Things to note:


Random.nextInt(10)


readLine()


readLine() ?: break


readLine()


while (!correct && tries < 3)


tries


tries


tries += 1


correct


guess == randomNumber


toIntOrNull


$randomNumber


randomNumber





Thank you so much for help. Could you please help little more, I also want this program to ask user either to quit or continue game again. Please help
– Zahid Khan
Jun 30 at 10:02






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Extract Id from Twitch Clip URL

Why are these constructs (using ++) undefined behavior in C?

I'm Still Waiting (Diana Ross song)