Search code examples
javarandomlogic

Random number generator generates the same number


I am a beginner in programming, currently learning java. As a part of my practice, I have created the below code, which is simply a game asking the user to guess the number generated randomly by the Computer, if the player guesses it correctly, the score increases by 5. The problem is that my Random Number generator every time generated the same number, no randomness at all,I want to solve this problem. And also I want a more intuitive approach for my this code. the code is mentioned below:

public static void main(String... args){
 System.out.println("\nGuessNumber is a game, in which the player is required to guess the number\n" +
                       "generated randomly by the computer. If the player guesses it right his score\n" +
                       "is increased to 5, no score is cut when losing. The number will be from 1 to 6\n" +
                       "inclusive.\n");
    Scanner scan = new Scanner(System.in);
    char input;
    int randomNumber;
    int playerScore =0 ;
    //int roundCounter = 0;
    do{ System.out.print("Press 'r' to play and 'q' to quit: ");
        input = scan.next().charAt(0);
        switch (input){
            case 'r':
                System.out.print("A random number is generated for you, guess what it is: ");
                int answer = scan.nextInt();
                if(answer == (randomNumber = generateRandom())){
                    System.out.print("Congrats! that was absolutely right guess, ");
                    playerScore += 5;
                }else{
                    System.out.print("Oops!, wrong guess, right answer is "+randomNumber +", ");
                }
                break;
            case 'q':
                System.out.println("Bye Bye!");
                break;
            default:
                System.err.print("Enter a valid input: ");
                break;
        }
    }while(input != 'q');

    System.out.println("You scored "+ playerScore);
}

 private static int generateRandom(){
    Random random = new Random(1);
    return random.nextInt(7);
}

and a sample output:

enter image description here

Edit: If you can provide a better approach to write this code, please suggest me


Solution

  • Do not specify same seed

    As commented, do not set the seed to the same number if you want different results. Same seed yields same results.

    Your code new Random(1) results in a number generator that generates the same sequence of outputs. Instead, call the no-arg constructor. Change this:

    Random random = new Random(1);
    

    … to this:

    Random random = new Random();
    

    The Javadoc for the no-arg constructor promises:

    This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

    Do not recreate generator

    Furthermore, you are needlessly recreating the random generator. Do not call new Random over and over again. Call it once, and then store a reference to the generator object on a variable for later use.

    ThreadLocalRandom

    I recommend using ThreadLocalRandom rather than Random. Doing so avoids concurrency problems if you ever add threads and executor services to your code. Another benefit is the many convenience methods offered on that class. And using this class makes the syntax so simple that there is no point to you creating a separate method. Just call:

    ThreadLocalRandom.current().nextInt( 7 )