# Thread: What won't this simple code work?

1. Member
Join Date
Mar 2012
Posts
10
Rep Power
0

## What won't this simple code work?

Java 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?")

2. ## 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

3. Moderator
Join Date
Apr 2009
Posts
13,324
Rep Power
23

## 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.

4. ## Re: What won't this simple code work?

Have you abandoned your previous thread then?
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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•