Does anyone have 2.19.4 “Guess a Number 2.0” code for CodeHS?
The correct answer and explanation is:
Sure! Here’s the correct solution for CodeHS 2.19.4 “Guess a Number 2.0”, which is typically part of the JavaScript (or Python) introductory course. This problem improves upon a basic guessing game by allowing multiple guesses and giving feedback if the guess is too high or too low.
✅ Correct JavaScript Code:
var start = 1;
var end = 100;
var number = Randomizer.nextInt(start, end);
var guess = readInt("Guess a number between " + start + " and " + end + ": ");
while (guess !== number) {
if (guess < number) {
println("Too low.");
} else {
println("Too high.");
}
guess = readInt("Guess again: ");
}
println("You guessed it!");
🧠 Explanation (approx. 300 words):
This program is a number guessing game that uses a while
loop to allow the user to continue guessing until they get the correct number. Let’s break it down step by step:
- Random Number Generation:
Randomizer.nextInt(start, end)
picks a random number between 1 and 100. This is the number the user has to guess. - User Input:
The first prompt asks the user to guess a number. The input is stored in theguess
variable. - Looping Until Correct:
Thewhile
loop continues to run as long as the guess does not equal the randomly generated number. This allows for multiple guesses. - Conditional Feedback:
Inside the loop, there’s anif...else
block that checks if the guess is too low or too high:- If the guess is less than the number, it prints “Too low.”
- If the guess is greater than the number, it prints “Too high.”
- Prompting Again:
After each incorrect guess, the program prompts the user again for another number, updating theguess
variable. - Correct Guess:
Once the guess matches the number, the loop ends andprintln("You guessed it!")
is executed, congratulating the player.
This code teaches key programming concepts: user input, random numbers, loops, and conditionals — all foundational for building interactive programs.