dimanche 21 juillet 2019

Random number in guessing game

I am trying to write a Number Guessing Game program, so the program generates a random number, and the program gives prompts as too high, too low, until the user gets its write. However, the Random generator either generates the same random number each time, or it says "too high" for one user input and then "too low" for the user input directly after/before

I have moved the random generator inside my while loop, and in that case, it says the input is "too high", and the number following it is "too low". When I move the Random Generator outside the loop, it just generates the same number for each irritation of the game.

import java.util.Scanner;
import java.util.Random;
public class numberGuessingGame
{

    public static void main (String[] args) 
    {
        int randomNumber, userNumber = 0, guesses = 0;
        final int MAX = 100;
        char playAgain, playGame = 'y'; 


        Random generator = new Random();


    //ask user if they wish to play   
        System.out.println("Would you like to play the Number Guessing" 
                        " y / n");
        Scanner scan = new Scanner (System.in);

        playGame = scan.next().charAt(0); 

//while loop to continue to execute game as long as the user enters 'y'

        while (playGame == 'y'){
        if (playGame != 'y') break;

        randomNumber = generator.nextInt(MAX) + 1;


        System.out.println("Please pick a number between 1 and 100.");
        userNumber = scan.nextInt();

        //high and low sugguestion
        if (userNumber > randomNumber)
        System.out.println("Number is too high, try something lower.");
        if (userNumber < randomNumber)
        System.out.println("Number is too low, try something higher.");
        if (userNumber == randomNumber) {
        System.out.println("That number is correct!");
        System.out.println("Would you like to play again? y/n");
        playGame = scan.next().charAt(0);
    }
        //counter to keep running total of times guessed
        guesses++;
        System.out.println("You have guessed " + guesses + " times!");


    }

    //break statement skips here when 'n' is entered in
    // the game prompting question
    System.out.println("Thanks for playing, have a nice day!");  


}

}

The program should be generating a new random number for each irritation of the game, which will be prompted after each correct guess of the randomNumber.




Aucun commentaire:

Enregistrer un commentaire