1

I have a problem where I'm trying to fill an array with 30 random integers from the range 1-300 with just a main method and one more method called LOAD(). For some reason my code below generates an array with my test statement System.out.println("Here are 30 random numbers: " + Arrays.toString(randomThirty)); but it's filled with only 0s and no other numbers in all fields.

import java.util.*;

public class randArray
{

public static void main(String args[])
{
     //main method which creates an array to store 30 integers

    int[] randomThirty = new int[30]; //declare and set the array randomThirty to have 30 elements as int type

    System.out.println("Here are 30 random numbers: " + Arrays.toString(randomThirty));

    LOAD(randomThirty); // the job of this method is to populate this array with 30 integers in the range of 1 through 300.

}

public static void LOAD(int[] randomThirty)
{
    // looping through to assign random values from 1 - 300
    for (int i = 0; i < randomThirty.length; i++) {
        randomThirty[i] = (int)(Math.random() * 301); 
}
}

}

artemd
  • 25
  • 1
  • 4

2 Answers2

12

The reason is that you print out the array first, and populate it second.

In other words, LOAD() doesn't get called until after you've printed out the array.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

u are printing before calling the method....change the order of calling and it will work

ashutosh raina
  • 9,228
  • 12
  • 44
  • 80