How to Generate a Number No More Than 4 Times in Java
Programmers will often find number generation useful, especially when random numbers are needed or specific patterns of numbers are required. Java programmers can generate random numbers through the "Random" library. Using a simple loop, a you can generate exactly four random numbers for use in your program.
Instructions
-
-
1
Set up your Java class to import the "Random" library:
import java.util.Random
public final class GenRandom{
public void main(){
}
} -
2
Create a random number generator variable, along with an array to store your random numbers:
public void main(){
Random generator = new Random();
int[] nums;
nums = new int[4];
} -
-
3
Create a "for" loop that generates a new random number on each iteration, and stores it into the array. This loop will iterate exactly four times. As a safeguard, you can enter code that ensures that if the number of iterations is greater than four, it will automatically change to four:
public void main(){
Random generator = new Random();
int[] nums;
nums = new int[4];
i = 4;//if programmer allows user input that changes i
if(i > 4){
i = 4;
}for (i; i >4; i++){
nums[i] = generator.nextInt(50) // generates random numbers between 0 and 50
}
}
-
1