user5947618
user5947618

Reputation:

Using random number generator Java

I'm having trouble using the random number generator, or having trouble understanding the concept entirely. I want to generate 20 random numbers from 0 to x.

Random ranNum= new Random();
int  n = ranNum.nextInt(x) + 0;

Is this how I would go about it?

Upvotes: 0

Views: 345

Answers (6)

Dodo
Dodo

Reputation: 25

    for (int i = 0; i < 20; i++) {
        double r = Math.random();
        int[] RandomNumbers= new int[20];
        RandomNumbers[i] = (int) (101. * r);
        System.out.println(RandomNumbers[i]);
    }

Upvotes: 0

pjs
pjs

Reputation: 19855

The following will create an ArrayList of values between 0 and x, inclusive, assuming that x has been previously defined as a positive int.

ArrayList<Integer> randNums = new ArrayList<Integer>();
Random r = new Random();
for(int i = 0; i < 20; ++i) {
    randNums.add(r.nextInt(x + 1)); 
}

You can then use the values however you wish (printing or in subsequent calculations) by iterating through the ArrayList.

Upvotes: 1

R. Gulbrandsen
R. Gulbrandsen

Reputation: 3778

I like Math.random(), it returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

public int getNumber(int max) {
    return (int) (Math.random() * max); //returns an int between 0 and max
}

public void main() {
    for(int i = 0; i < 20; i++) {
        System.out.println(getNumber(100));
    }
}

Prints 20 numbers between 0 and 100, for more info about Math.random() https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

Upvotes: 0

Tyler
Tyler

Reputation: 1

Depends on what you need the numbers for.

To print them, you would:

Random randNum = new Random();
    for(int x = 0; x < 20; x++){
        System.out.println(randNum.nextInt(20));
    }

Put in ArrayList and print out:

    ArrayList<Integer> list = new ArrayList<Integer>();
    Random randNum = new Random();
    for(int x = 0; x < 20; x++){
        list.add(randNum.nextInt(x)); //must set x to set maximum number it can be
    }
    for(int a : list)
        System.out.println(a);

Upvotes: 0

Hans Dieter
Hans Dieter

Reputation: 1

With this you create 20 random numbers. I still didn't understand wheter you wanna have duplicates in your random numbers or not. Well, try this:

static Random r = new Random();
private static final int number = 5;

public static void main(String[] args) {
    for(int i =0; i<20;i++){
        System.out.println(r.nextInt(number));
    }

}

Upvotes: 0

Denis
Denis

Reputation: 1229

Run this code:

int x=100,n=0;
Random ranNum= new Random(); 
for(int i=0;i<20;i++)
 {
   n = ranNum.nextInt(x);
   System.out.println(n);
 }

X is the range of random number. this program generate random number between 0 to 100.If you want to specify a min value than you can try this line inside the loop:

n = ranNum.nextInt(x-min)+min;

Upvotes: 0

Related Questions