Java的NullPointerException异常与数组对象 [英] Java NullPointerException with objects in array

查看:143
本文介绍了Java的NullPointerException异常与数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Java和得到一个NullPointerException异常错误与该行此code:

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

下面是整个程序code:

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;
        }
    }
}

}

最后一个函数应该把一个DominionTile在数组中的每个地方。我在做什么错了?

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

推荐答案

您在构造函数都没有了。此声明并分配给一个局部变量,而不是施皮尔费尔德字段,因此场留下了一个价值

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];

您可能希望:

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.

这篇关于Java的NullPointerException异常与数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆