自定义setRandom的范围可以通过以下几种方式实现:
public void setRandom(int min, int max) {
Random random = new Random();
int randomNumber = random.nextInt(max - min + 1) + min;
this.randomNumber = randomNumber;
}
enum Range {
LOW(1, 10),
MEDIUM(11, 20),
HIGH(21, 30);
private final int min;
private final int max;
Range(int min, int max) {
this.min = min;
this.max = max;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}
public void setRandom() {
Random random = new Random();
int randomIndex = random.nextInt(Range.values().length);
Range range = Range.values()[randomIndex];
int randomNumber = random.nextInt(range.getMax() - range.getMin() + 1) + range.getMin();
this.randomNumber = randomNumber;
}
// 配置文件范例:range.json
{
"min": 1,
"max": 100
}
public void setRandom() {
try (InputStream inputStream = getClass().getResourceAsStream("range.json")) {
JSONObject config = new JSONObject(new JSONTokener(inputStream));
int min = config.getInt("min");
int max = config.getInt("max");
Random random = new Random();
int randomNumber = random.nextInt(max - min + 1) + min;
this.randomNumber = randomNumber;
} catch (IOException e) {
e.printStackTrace();
}
}
请注意,以上示例中的代码仅为演示目的,实际使用时需要根据具体的编程语言和框架进行相应的调整和实现。
领取专属 10元无门槛券
手把手带您无忧上云