0

I'm trying to create a bunch of the same objects (Grass) with a loop in different spaces. I have a grid and I want it to fill up the entire grid with different colors. So I have this code so far:

public stage() {
    super(null);

    cast = new Cast();
    cast.setBounds(10, 10, cast.getWidth(), cast.getHeight());
    this.add(grid);

    for (int i = 0; i <= 19; i++) {
        obj = new Object[] {
           new Grass (cast.cells[i][i])  
        };
    }
}

This obviously doesn't work and only makes a colored cell in the last spot of the grid. Is there anyway to make a loop for objects in every spot?

3
  • You've reassigned obj to a new array each time through the loop... What are you expecting to happen? Can you use an ArrayList? Commented Aug 25, 2016 at 17:59
  • Look up how Arrays (or Lists) and For loops work. Commented Aug 25, 2016 at 17:59
  • And grass is only on the main diagonal of the matrix? Commented Aug 25, 2016 at 17:59

1 Answer 1

1

Your code is going to create an new Object[1] 20 times. That Array will contain an instance of Grass. Try this instead.

public stage() {
    super(null);

    cast = new Cast();
    cast.setBounds(10, 10, cast.getWidth(), cast.getHeight());
    this.add(grid);

    Object obj[] = new Object[20];

    for (int i = 0; i <= 19; i++) {
       obj[i] = new Grass (cast.cells[i][i])l
    }
}
}
Sign up to request clarification or add additional context in comments.

4 Comments

note you have typo on >obj[i] = new Grass (cast.cells[i][i])l There is an l in place for ; There is also an extra } at the end.
There is also the problem with the original question. In your case the array of Grass objects goes out of scope immediately after filling it. The array either needs to be a member variable or needs to be passed into another object to hold onto it.
Thanks for the suggestion, however, I realized the code I had originally put was incorrect and only would create grass diagonally. The answer you have gave worked, however what would be the best way to create the grass on the entire grid?
I have just realized what you meant by the array of Grass objects going out of scope. How would I make the array a member variable or pass into another object?

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.