Rodbrollin Rodbrollin - 1 month ago 5
Java Question

How do I get the output to produce random numbers?

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.

Answer

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]);
        }