-1

So i have two methods to create a randomized array and arraylist with 100 random integers. For some reason only the arraylist works though. Not sure what is wrong. Can someone take a look at it? I really don't know why it doesn't work. Is there a better way to randomize an array?

public static int[] gen1()
  {
    int[] no = new int[100];
    for(int i=0;i<no.length;i++)
    {
        no[i] =(int)(Math.random());
    }
    return no;
}   

public static ArrayList<Integer> gen2()
{
    ArrayList<Integer> oh = new ArrayList<Integer>();
    Random random = new Random();
    for (int i = 0; i < 100; i++)
    {
        oh.add(random.nextInt());
    }
    return oh;
}

public static void main(String[] args)
{   
    System.out.println("Original Array:");
    System.out.println(gen1());
    System.out.println("Original List:");
    System.out.println(gen2());
}
user5344755
  • 47
  • 2
  • 6

1 Answers1

0

Math.random() returns a double between 0 and 1 (exclusive), so casting it to int will always return 0. That's the reason your array will contain only 0s.

On the other hand, random.nextInt(), used to populate the ArrayList can return any of the possible int values.

Eran
  • 387,369
  • 54
  • 702
  • 768