0

This is what I have so far

    import java.util.Arrays;

public class Randoms {

    public static void main(String[] args) {
        int[] array = new int [50];
        for (int index = 0; index < array.length; index++) {
            int j = (int) Math.random() * 101 + 1;

            System.out.println(j);
        }

    }

}

My output just produces a bunch of 1s. I want numbers from 0-100? Any help would be appreciated. I am fairly new to Java so sorry if this is a really dumb mistake. Thanks in advance.

Rodbrollin
  • 49
  • 5

2 Answers2

0

You want to use the java.util.Random which would be something like:

Random random = new Random();
int yourRandomNumber = random.nextInt(100);

This will print out a random number between 0 and 100. You can read about Random here. If you want a number between 1 - 100 you would do:

Random random = new Random();
int yourRandomNumber = random.nextInt(99)+1

If you want a bunch of random numbers, you can do:

    Random random = new Random();
    int[] array = new int [50];
    for (int index = 0; index < array.length; index++) {
        int yourRandomNumber = random.nextInt(99)+1
        System.out.println(yourRandomNumber);
    }

If you are set on using Math.random you would do:

int yourRandom =  Min + (int)(Math.random() * ((Max - Min) + 1))
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
0

If you type-cast it to int it will round down to 0. Because it first calculates the (int) Math.random()

try the following code :

 for (int index = 0; index < array.length; index++) {
           array[index] =  (int)(Math.random() * 100);
            System.out.println(array[index]);
        }
thetraveller
  • 445
  • 3
  • 10