Reputation: 17
I am currently starting understanging Java. So while I've been trying to develop some minesweeper application I noticed, that when trying to add coordinates to a "Mines[]" array, the debugging window opens and my application doesn't continue displaying the purposed Minefield.
So that's my code:
package com.ochs.minesweeper;
public class MineField {
public Mine[] mines;
public MineField(int xMines, int yMines) {
mines = new Mine[xMines*yMines];
int xCounter = 0;
int yCounter = 0;
for(int i = 0; i < yMines; i++) {
for(int j = 0; j < xMines; j++) {
mines[i*j].setX(xCounter);
mines[i*j].setY(yCounter);
xCounter += 100;
}yCounter += 100;
}
}
}
Even when I just try something like:
for(int i = 0; i < xMines*yMines; i++) {
mines[i].setX(2);
}
or something like that it seems like I can't use the variable of the for-loop in my array to process...
Does anyone has an idea what I am doing wrong? I just want my MineField to have it's Mine[] array. This Mines are all created in the for loop with different coordinates so that they can be displayed in a grid on my surfaceview. Does anyone has an idea? Or maybe another solution how I can create a simple grid of objects, in my example mines?
Thanks in advance!
Upvotes: 0
Views: 78
Reputation: 163
There is a problem with where you are setting the coordinates in this bit of code:
mines[i*j].setX(xCounter);
mines[i*j].setY(yCounter);
For example, the coordinates (x=2, y=3) and (x=3, y=2) refer to different locations on the grid, however 2*3=6 and 3*2=6. You need slightly more complicated logic to get a unique index for every coordinate (semihyagcioglu's approach is much better):
public MineField(int xMines, int yMines) {
mines = new Mine[xMines*yMines];
int xCounter = 0;
int yCounter = 0;
for(int i = 0; i < yMines; i++) {
for(int j = 0; j < xMines; j++) {
mines[i+(j*yMines)].setX(xCounter);
mines[i+(j*yMines)].setY(yCounter);
xCounter += 100;
}yCounter += 100;
}
}
The reason the application crashes is that you need to instantiate each mine object in your Mine[]
array before trying to call setX()
and setY()
on them.
for (int i=0; i< (xMines*yMines); i++)
Mine[i] = new Mine();
Upvotes: 1
Reputation: 4101
Why not use 2 dimensional arrays? You can define Mine[][] mines
and then in the loop:
for(int i = 0; i < yMines; i++) {
for(int j = 0; j < xMines; j++) {
mines[i][j].setX(xCounter);
mines[i][j].setY(yCounter);
xCounter += 100;
}yCounter += 100;
}
Upvotes: 1