简体   繁体   中英

how to generate random numbers using a while loop in java?

i need to generate random numbers from 1 to 20 and count their sum until it reaches over 100

Random rand = new Random();
 int num = rand.nextInt(20)+1;
 System.out.println("Random number " + num);
 int sum = num;
 System.out.println("Current sum " + sum);
 num = rand.nextInt(20)+1;
 sum = num + num;
 System.out.println("Random number " + num); 
 System.out.println("Current sum " + sum);
 while (sum > 100)
 { 
     System.out.println("The sum " + sum + " exceeds 100"); 
 }

this is what i have so far

Here is a rather interesting way to do it.

  • generate a stream of ints between 1 and 20 inclusive.
  • turn into an iterator.
  • continue summing until the sum > 100.
Random rand = new Random();
int sum = 0;
for (Iterator<Integer> it = rand.ints(1, 21).iterator();
        sum < 100 && it.hasNext();) {
    sum += it.next();
}

Or even better as it avoids unboxing.

int sum = 0;
while ((sum += rand.nextInt(20)+1) < 100);
System.out.println(sum);

You need to put the generation and sum inside the loop. You can't use the same variable ( num ) to hold two values. You were making the sum equal to two nums, not actually tracking the sum of the nums.

You need to put the termination statement outside the loop. and initialise your sum outside the loop.

Random rand = new Random();
int sum = 0; //initialise your sum

while (sum < 100) // this equality was the wrong way around
 { 
    int num = rand.nextInt(20)+1;
    System.out.println("Random number " + num);

    sum += num; //add your random num to the sum
                //  don't just make it equal to two nums.
    System.out.println("Current sum " + sum);
 }
 System.out.println("The sum " + sum + " exceeds 100"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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