The assignment here is to write a simple game where the user tries to guess a randomly selected number. After each guess the application tells the user if the guess is too high or too low. This is repeated until the user finally guesses the number.
First thing we need is to generate a random number. To achieve this Java provides the java.util.Random class with its nextInt() method providing exactly what we need (see line 31).
Then we want to repeatedly prompt the user to guess the number until they get it right. For this we can use a while loop (see line 36). For each loop iteration we prompt the user to make a guess, and read their input. That input is then compared with the random number we generated earlier.
And that’s about, look over the code and ask if anything isn’t clear. Or better still become a member and one of our Java mentors can guide you.
package com.learnjava.console; import java.util.Random; import java.util.Scanner; /** * Write a guessing game where the user tries to * guess the number randomly picked by the computer. * For each guess tell the user if the * guess is too high, low or correct. * * @author https://learn-java-by-example.com * */ public class HighLowGuessingGame { public static void main(String[] args) { // Create a random number generator Random random = new Random(); // Use Scanner for getting input from user Scanner scanner = new Scanner(System.in); // Use the random generator to // pick a number between 0 and 99 (inclusive) int number = random.nextInt(100); int guess = -1; // Loop until the user has guessed the number while (guess!=number) { // Prompt the user for their next guess System.out.print("Enter your guess: "); // Read the users guess guess = scanner.nextInt(); // Check if the guess is high, low or correct if (guess<number) { // Guess is too low System.out.println("Too low, please try again"); } else if (guess>number) { // Guess is too high System.out.println("Too high, please try again"); } else { // Guess is correct !! System.out.println("Correct, the number was " + number); } } } }
great example , I always believe that game programming can improve your programming drastically.
hi this is great code thanks fam.
how can we keep track of the number of times the user guess?
To track the number of times add a counter and increment it overtime the user makes a guess.
Will look to add an example of that in the future.
Well I guess I don’t have to spend the weekend fiugirng this one out!