Darius
Darius

Reputation: 155

Java NullPointerException with objects in array

I'm new to Java and getting an NullPointerException error with this code at this line:

spielfeld[i][j] = new DominionTile(world,i,j); // last function

Here is the whole program code:

public class MapProvider implements ....... {
private DominionTile[][] spielfeld;

int row;
int col;
public MapProvider(int zahl1, int zahl2) {
    DominionTile[][] spielfeld = new DominionTile[zahl1][zahl2];
    col = zahl1;
    row = zahl2;
}

@Override
public MapTile[] getColumn(int spalte) { // DONE
    if ((spalte < 0) && (spalte > col) ) {
        return null;
    }
    else {
        return spielfeld[spalte]; 
    }
}

@Override
public int getColumns() { // DONE
    return col;
}

@Override
public int getRows() { // DONE
    return row;
}

@Override
public boolean isValid(int spalte, int zeile) { // DONE
    if ((spalte < 0) && (zeile < 0)) {
        return false;
    }
    else if ((spalte > col) && (zeile > row)) {
        return false;
    }
    else {
        return true; 
    }
}

@Override
public DominionTile getTile(int col, int row) { // DONE
    return spielfeld[col][row]; 
}

@Override
public void setupMapTiles(MapWorld world) { // NICHT FERTIG
    final Map karte = world.getMap();
    int zeilen = karte.getRows();
    int spalten = karte.getColumns();
    for (int i = 1; i <= spalten; i++) { // I-TE SPALTE
        for (int j = 1; j <= zeilen; j++) { // J-TE ZEILE
            spielfeld[i][j] = new DominionTile(world,i,j);
            //DominionTile neu = new DominionTile(world, i, j);
            //spielfeld[i][j] = (DominionTile)neu;
        }
    }
}

}

The last function should put a DominionTile in each place of the array. What am I doing wrong?

Upvotes: 1

Views: 421

Answers (2)

xcoder
xcoder

Reputation: 1436

As a starting point, you might want print out the values of zeilen and spalten. I am guessing this is caused by accessing spielfeld[i][j] where spielfeld[i] does not exist in the first place.

Upvotes: 0

clstrfsck
clstrfsck

Reputation: 14829

You have this in your constructor. This declares and assigns to a local variable, not the spielfeld field, and hence the field is left with a null value.

DominionTile[][] spielfeld = new DominionTile[zahl1][zahl2];

You probably want:

public MapProvider(int zahl1, int zahl2) {
    spielfeld = new DominionTile[zahl1][zahl2];
    col = zahl1;
    row = zahl2;
}

i.e. without the type declaration, which will assign to the object's field.

Upvotes: 4

Related Questions