简体   繁体   English

Random()不生成随机数

[英]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. 我正在尝试使用roshambo(或Rock-Paper-Scissors),并让计算机输出Rock,Paper或Scissors来代替0到2之间的随机值。但是,我没有获得随机值。 When the program runs it goes through a while loop, and each time it goes through the loop, the value remains the same. 程序运行时会经历while循环,每次经历循环时,该值均保持不变。 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. 我在do-while循环之外调用了p2.generateRoshambo()。 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. 症状的最可能原因是每次都创建一个新的Random实例。 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. 重要的是,创建尽可能少的Random实例(通常在程序中只有一个实例),然后继续从中获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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