# What won't this simple code work?

• 04-12-2012, 11:40 AM
xpl0rerchr
What won't this simple code work?
Code:

```    public World(int numTypeA, int numTypeB) {         city = new Organism[ROWS][COLS];         rand = new Random();         while (numTypeA > 0) {             Coordinates temp = new Coordinates(rand.nextInt(ROWS), rand.nextInt(COLS));             if (city[temp.row][temp.col] == null) {                 city[temp.row][temp.col] = new TypeA(this, temp);                 numTypeA--;             }         }         while (numTypeB > 0) {             Coordinates temp = new Coordinates(rand.nextInt(ROWS), rand.nextInt(COLS));             if (city[temp.row][temp.col] == null) {                 city[temp.row][temp.col] = new TypeB(this, temp);                 numTypeB--;             }         }     } public class Coordinates {     int row;     int col;     Coordinates(int x, int y) {         this.row = x;         this.col = y;     } }```
By doing the above, I'm trying to randomly place TypeA and TypeB objects (which both extend Organism) in city[ROWS][COLS].
The problem is that apparently they are created at city[column][row] each time, instead of city[row][column]. Can anyone see why this would happen?

(PS. I meant to say "Why won't this simple code work?")
• 04-12-2012, 12:33 PM
JosAH
Re: What won't this simple code work?
Maybe there is confusion about what the row index is and what the column index is. A two dimensional array is just an array of one dimensional arrays. The first index denotes a one dimensional array and the second index is an index value for that one dimensional array. The first index is called the 'row index' while the second one is called the 'column index'. Two dimensional arrays are said to be in 'row major order'.

kind regards,

Jos
• 04-12-2012, 12:35 PM
Tolls
Re: What won't this simple code work?
Stick some println() calls in there to see what's going on in that code.
Debugging it is the only way you'll know what values Java is actually using, so print out the coordinates each time and then the city array (possibly) to see where everything's ended up.
That code there seems to have row/column laid out the same everywhere, so I doubt it's that.
• 04-12-2012, 02:54 PM
DarrylBurke
Re: What won't this simple code work?
http://www.java-forums.org/new-java/...nt-reason.html

Common courtesy would dictate that you tell us there that your problem is solved.

And I wouldn't construct a new Random object each time into the method, especially when it's already declared as a field.

db