1

I have this code:

public static int MAX;
public static int MIN;


public static void startGame(){

    MIN = -1;

    MAX = 1;

    int[] randomGridVals = new int[ROWS*COLUMNS];

    fill(randomGridVals);

    System.out.println(Arrays.toString(randomGridVals));

    <MORE CODE>
}

private static void fill(int[] randomGridVals) {

    for(int i = 0 ; i < randomGridVals.length; i++)
    {
        int rnd = MIN + (int)(Math.random() * ((MAX - MIN) + 1));

        randomGridVals[i] = rnd;
    }

}

I expect that the array is passed by reference and the array have random values in it however when I try to print it its empty. Why is this happening ?

8
  • What are the values of MIN and MAX? Commented Jan 27, 2012 at 23:48
  • Sorry, they are basically the range for the random function. I updated the code Commented Jan 27, 2012 at 23:49
  • Your code look, and works fine for me. I used MAX = 222 and MIN = 111. Commented Jan 27, 2012 at 23:51
  • 3
    What are the values of ROWS and COLUMNS? (And note that ALL CAPS implies these are constants of some sort.) Commented Jan 27, 2012 at 23:53
  • Strange, I will give it a try. Commented Jan 27, 2012 at 23:53

3 Answers 3

4

Hard to say for sure from the code you have provided. I would check the value of ROWS*COLUMNS. That is probably 0 and thus you create a 0 sized array.

Sign up to request clarification or add additional context in comments.

3 Comments

I am sure the constants are fine since I use them to construct a grid.
Since the code prints [], that's proof that ROWS*COLUMNS = 0.
@Cemre - when do you set ROWS and COLUMNS. They really should be set at declaration, since they are all caps and that means "static final". My guess is that you set them after running this routine.
2

Java is never pass by reference. It's always pass-by-value.

As for being empty, please post ROWS and COLUMNS or check them.

Comments

1

Where are you defining ROWS and COLUMNS? At least one of them must equal 0, rendering your data structure an int[0].

Since int is a primitive type, your array starts out filled with 0s. Since arrays can't be resized, and Arrays.toString will print every cell (it won't just skip 0s- 0 is usually pretty important in an int[], for one thing!), this result cannot be an artifact of your array not being written into. It must have been initialized to length 0, and that means that ROWS * COLUMNS == 0. Check the value of ROWS, of COLUMNS, and also their types- surprising types other than int might in rare cases cause this, but the 0 is more likely.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.