首页 > 解决方案 > 如何从范围中排除零

问题描述

我正在学习 Java,处于初级阶段。我正在尝试打印骰子结果,所以从 1 到 6。

//instance of random class
Random DICE = new Random();

int DiceRange = 7;


int RIGHT = DICE.nextInt(DiceRange);
int LEFT = DICE.nextInt(DiceRange);


System.out.println("Right Dice = " + RIGHT);
System.out.println("Left Dice = " + LEFT);

此代码有时也会打印“零”的问题。我想保持范围从 1 到 6,而不是 0 到 6。我尝试执行以下操作,但没有奏效:

int i = 0;

while (DiceRange == 0); {
    i++;
}

CPU 达到 100% :)

那么如何排除零呢?

标签: javaintegerrangedice

解决方案


随机文档

public int nextInt(int bound)

返回介于 0(包括)和指定值(不包括)之间的伪随机、均匀分布的 int 值

因此,从您的代码开始,您可以使用以下方法解决您的问题:

Random DICE = new Random();
int DiceRange = 6;
int RIGHT = DICE.nextInt(DiceRange) + 1;
int LEFT = DICE.nextInt(DiceRange) + 1;

推荐阅读