Reputation: 11
I am currently working on creating a random number generator for an assignment in my programming class. The requirements are as follows:
Write a well-documented (commented) program, “RanNumGen,” that takes an integer command-line argument “n” that indicates the number of random numbers to generate and uses the method “Math.random()” to print uniform random values between 1 and 100 (both inclusive), and then prints the minimum and maximum value. [MO1.1, MO1.2]
Sample runs would be as follows.
java RanNumGen 5 67 24 31 11 80 The minimum value is 11. The maximum value is 80.
java RanNumGen 8 2 76 29 96 91 98 35 16 The minimum value is 2. The maximum value is 98.
So far I am able to generate random integers with the code I've written. However it only generates 5 random numbers between 1-100 and it is not based on what I input when I attempt to run the program. Below is the code I've written:
public class GenerateRandomNumber
{
public static void main(String[] args)
{
//define range
int max = 100;
int min = 1;
int range = max - min + 1;
//generate random numbers within 1 - 100
for (int n = 1; n < 6 ; n++) {
int rand = (int) (Math.random() * range) + min;
//output is different everytime code is executed
System.out.println(rand);
}
}
}
When I attempt to run the program I receive:
java RanNumGen 2
20 15 89 34 7
----I am getting 5 random integers instead of the 2 as requested.
If anyone has any suggestions it would be GREATLY appreciated!
Upvotes: 1
Views: 594
Reputation: 71
The command line values are passed to the main
method as an array of strings. As you have only one input, You can read the input value from the array with the index=0
and parse that to Integer.
Upvotes: 0
Reputation: 201477
Because you are ignoring the command line arguments entirely. And using a hardcoded six and one here (6 - 1
is 5
):
for (int n = 1; n < 6 ; n++) {
Try something like
int count = 5;
if (args.length > 0) {
count = Integer.parseInt(args[0]);
}
for (int n = 0; n < count; n++) {
To default to a count
of 5
. And check if there are any command line arguments, if there are parse the first one and update count
.
Upvotes: 2