简体   繁体   English

如何在给定的时间内将随机生成的数字保持相同?

[英]How do I keep a randomly generated number the same within a given method for a certain period of time?

What I want to do is generate a random number that determines a color. 我想做的是生成确定颜色的随机数。 This color changes every time count is a multiple of 3. When count is 0, 1, 2, the color should stay the same. 每次计数为3的倍数时,此颜色都会更改。当count为0、1、2时,颜色应保持不变。 It should then change at 3. 然后应在3处更改。

count changes every time that the method printColor() is run. 每次运行方法printColor()时count更改。

I've tried doing this as you can see below, but I keep getting a NullPointerException. 我已经尝试过这样做,如下所示,但是我一直收到NullPointerException。 I cannot generate the randomNumber in the field or in a constructor as that is outside of the constraint of requirements. 我无法在字段或构造函数中生成randomNumber,因为这超出了需求的限制。

import java.awt.*;
import java.util.*;
public class ColorGenerator {

private int count = 1;
private Random rand;
private int randomNumber;

public Color getColor(){
    Color lionColor = Color.RED;
    if (count % 3 == 0 || count == 1){
        randomNumber = rand.nextInt(3) + 1;     
    }
    if (randomNumber == 1){
        lionColor = Color.RED;
    } else if (randomNumber == 2){          
        lionColor = Color.BLUE;
    } else {
        lionColor = Color.GREEN;
    }
    return lionColor;
}

public void printColor(Color color){
     count++;
     System.out.println(color.toString());
}

}

You need to initialize rand . 您需要初始化rand Change 更改

private Random rand;

to

private Random rand = new Random();

Note that since you start at 1, there will only be 2 consecutive colors the first run. 请注意,由于从1开始,第一次运行将只有2种连续颜色。 I recommend you to start count at 0 and drop the || count == 1 我建议您从0开始计数,并降低|| count == 1 || count == 1 (since when count = 0, count % 3 == 0 will hold). || count == 1 (因为当计数= 0时, count % 3 == 0将成立)。

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

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