1

I am learning Java, at a very beginning level. I am trying to print the Dice result, so from 1 to 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);

The issue with this code that "Zero" is also printed sometimes. I want to keep the range from 1 to 6, instead of 0 to 6. I tried to do the following, but did not work:

int i = 0;

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

The CPU went to 100% :)

So how to exclude zero from this?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 3
    Fix the upper limit of the range to 6 instead of 7 (generates a number between 0 and 5) and just add 1 to the result. That `while` doesn't make much sense anyway. – Federico klez Culloca May 26 '20 at 09:59
  • Does this ([this](https://stackoverflow.com/a/363691/133203) answer in particular) answer your question? [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – Federico klez Culloca May 26 '20 at 10:02
  • the while would theroretically work (albeit still being silly) if you didn't put the semicolon after the condition. that just makes an infinite loop `while (DiceRange == 0);`, followed by an unreachable scoped codeblock `{ i++; }` – Felk May 26 '20 at 10:12
  • @Felk that wouldn't be the only problem. How would incrementing `i` make `DiceRange` not 0? – Federico klez Culloca May 26 '20 at 10:22
  • just an english thing: "dice" = plural "die" = singular ;-) – JoSSte May 26 '20 at 10:22

1 Answers1

2

From Random documentation:

public int nextInt(int bound)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

So starting from your code you can solve your problem using :

Random DICE = new Random();
int DiceRange = 6;
int RIGHT = DICE.nextInt(DiceRange) + 1;
int LEFT = DICE.nextInt(DiceRange) + 1;
dariosicily
  • 4,239
  • 2
  • 11
  • 17