mardi 25 mai 2021

Need help in creating ' Guesing Game ' in Kotlin. Unable to check for previous input number and match it with current input number

I hope you all hear about ' Guessing Game '. The user has to guess a number and then the match goes on with generated Random number. Now, I have written code for this, but there is a glitch and that is I am unable to understand how to write the condition for -> count variable not getting increased by 1 if just previous input number is same as the current input number by the user.

I am putting my code here:

import java.util.*
import kotlin.random.Random.Default.nextInt

fun main() {

    val randomNumber = (1..100).random()
    println(randomNumber)
    var count: Int = 0
    
    while (true){
    val reader = Scanner(System.`in`)
    var inputNumber: Int = reader.nextInt()
    println("input number: $inputNumber")


    if (randomNumber == inputNumber) {
        println("You guessed it correct")
        count += 1
        print("You took $count guesses")
        break
    } else if (randomNumber > inputNumber) {
        println("You guessed it too small")
    } else {
        println("You guessed it too large")
    }
    count += 1
    print("Guess count: $count")


}

Desired output:

input number: 12
You guessed it too small
Guess count: 1

input number: 25
You guessed it too large
Guess count: 2

input number: 25
You guessed it too large
Guess count: 2

input number: 20
You guessed it right
Guess count: 3

My output:

input number: 12
You guessed it too small
Guess count: 1

input number: 25
You guessed it too large
Guess count: 2

input number: 25
You guessed it too large
Guess count: 3

input number: 20
You guessed it right
Guess count: 4

Aucun commentaire:

Enregistrer un commentaire