import java.util.Random; public class Number9 { /** * This method counts how many random numbers between 1 and 100 (inclusive) are * needed to get them to sum to at least 100. * @return The number of random integers between 1 and 100 (inclusive) used. */ public static int numRandNumsTo100() { // declare a variable of type Random and intialize it to the output // of the default constructor for the Random class which is an object // the ouputs random numbers when you call one of its methods Random randNumGen = new Random(); int sum = 0; int count = 0; int randomInt = 0; // repeatedly select a random number and add to sum until bigger or equal to 100 while (sum < 100) { // get the next random integer between 0 and 100 (exclusive) and add 1 randomInt = randNumGen.nextInt(100) + 1; // add the random number to the sum and add 1 to the count sum = sum + randomInt; //alternatively count = count + 1 count++; } // we know the sum is now >= 100 and the body of the while loop ran count times // so count random numbers were used and we want to RETURN this information to // whoever called this method. They may not want it printed to the screen! return count; } }