I am generating a random number between 1 and 6. And I have an integer value with a value of 0 (int number1 = 0;). I need to add them in a loop. Each round of the loop the random number will be generated again and add on top of the previous sum. How can I write in JAVA (console).
will continue until a sum of 100
int number1 = 0;
int number2 = (int) (Math.random () * 6 + 1);
for example: if number2 come 3 number1 (0) + number2 (3) = 3
and next tour if number2 come 4 number1 (3) + number2 (4) = 7
There can be many ways to do it. A simple way to do it is by using an infinite loop which you can break when
number1 == 100. It's also important to checkif (number1 > 100)after adding a random number and remove that random number if ittrue.A sample run:
To avoid casting the generated random numbers to
int, I recommend you useRandom#nextInt(int bound)as shown below: