简体   繁体   中英

Random() not generating random number

I'm trying to do roshambo (or Rock-Paper-Scissors) and have the computer output Rock, Paper, or Scissors in place of a random value from 0 to 2. However, I'm not getting random values. When the program runs it goes through a while loop, and each time it goes through the loop, the value remains the same. However, if I stop, then re-run the application, the value changes, and remains that same value for the duration of the loop. Am I coding this method correctly?

public class Player2 extends Player{

    private Random rand;

    public Player2(){
        rand = new Random();
    }

    public Roshambo generateRoshambo() {
        int min = 0;
        int max = 2;
        int randomNum = rand.nextInt(max - min + 1) + min;

        if(randomNum == 0){
            return Roshambo.ROCK;
        } else if (randomNum == 1) {
            return Roshambo.PAPER;
        } else {
            return Roshambo.SCISSORS;
        }
    }
}

Here is the loop:

Roshambo value = p2.generateRoshambo(); 
String cont = "Yes";

do{

        System.out.print("\nRock, Paper, or Scissors: ");
        String choice = sc.nextLine();


        System.out.println("\n" + name + ": " + choice);
        System.out.println("Computer: " + value);

        if (value == ...)
        {
            System.out.println("\n" + name + " Wins!\n");
        } 

        else if (value == ...)
        {
            System.out.println("\nYou Tied!\n");
        }

        else 
        {
            System.out.println("\nThe Computer Wins!\n");
        }

        System.out.print("Play again? (Yes/No): ");
        cont = sc.nextLine();
    } while (cont.equalsIgnoreCase("Yes"));

I just realized my own mistake. I called p2.generateRoshambo() outside of my do-while loop. By putting the following in my loop, I was able to solve the problem:

Roshambo value = p2.generateRoshambo()

The most likely cause of the symptom is creating a new Random instance each time round. The default seed is based on a clock that may not have ticked in a tight loop. It is important to create as few Random instances a possible, usually only one in a program, and go on getting values from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM