我是Kotlin的新手,我想在3次循环后限制while循环停止,请帮忙!此外,它还应要求用户退出游戏或继续
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.")
答案 0 :(得分:0)
尝试一下。
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")
}
注意事项:
Random.nextInt(10)
实际上将返回0到9之间的数字,因此您需要加1。readLine()
返回null,则没有更多内容可读取,因此如果readLine() ?: break
为null,readLine()
将返回一个字符串或立即停止循环。while (!correct && tries < 3)
表示在猜测不正确且tries
未达到3的情况下继续。tries
在每个猜测中增加1(tries += 1
)。 correct
跟踪是否已猜出正确的数字(guess == randomNumber
)。toIntOrNull
将String转换为Int,但实际上不是数字则返回null。$randomNumber
将randomNumber
的值直接放在字符串中,以便您可以将其作为消息的一部分进行打印。