An exercise asks that we extend the below random number generator app to print to the console how many times the user guessed before guessing the correct random number.
I first declared what I call a counter variable numberOfGuesses
inside the keepPlaying
while loop and then inside the continueGuessing
while loop I increment this number by 1 before I check the user's guess against the random number generated. This works, but then I tried declaring numberOfGuesses at the top of the program and commented out the former placement, as you can see below, and this also worked.
My question is, which is the better way of these two to solve this, and is there another even better way to solve this problem by using another loop perhaps or would that be silly/overkill/not workable?
var randomNumber = 1
var numberOfGuesses = 0
var continueGuessing = true
var keepPlaying = true
var input = ""
while keepPlaying {
//get a random number between 0 - 100
randomNumber = Int(arc4random_uniform(101))
print("The random number to guess is: \(randomNumber)")
//var numberOfGuesses = 0 //can go here, or in global variables up top!
while continueGuessing { //
print("Pick a number between 0 and 100.")
//get keyboard input, and trim the new line
input = String(bytes: FileHandle.standardInput.availableData, encoding: .utf8)!
input = input.trimmingCharacters(in: .whitespacesAndNewlines)
if let userGuess = Int(input) {
numberOfGuesses += 1
if userGuess == randomNumber {
continueGuessing = false //terminator for this while loop
print("Correct number!")
print("You have made this number of attempts to get it right: \(numberOfGuesses)")
} else if userGuess > randomNumber {
//user guessed too high
print("Your guess is too high!")
} else {
//no reason to check if userGuess < randomNumber. It has to be.
print("Your guess is too low!")
}
} else {
print("Invalid guess, please try again.")
}
}
print("Play again? Y or N")
input = String(bytes: FileHandle.standardInput.availableData,encoding: .utf8)!
input = input.trimmingCharacters(in: .whitespacesAndNewlines)
if input == "N" || input == "n" {
keepPlaying = false //a way to exit while loop
print("You have played the game this number of times: \(numberOfGuesses)")
}
continueGuessing = true
}