In: Computer Science
Create a class called RandomWhen.
The program must continuously generate a random number between 1 and 100 inclusive. The program must stop when the number 1 is generated, and the loop iteration will be printed. Run the program 3 different times.
Sample output:
It took ## iterations to generate a 1.
It took ## iterations to generate a 1.
It took # iterations to generate a 1.
Java Code:
import java.util.Random;
class RandomWhen {
public static void main(String[] args) {
int min = 1;
int max = 10;
int count = 0;
Random rand = new Random();
int randomnum = 0;
while(randomnum != 1)
{
randomnum = rand.nextInt((max - min) + 1) + min;
count++;
}
System.out.println("It took "+count+" Iteration to generate a 1.");
}
}
Screenshots: