您正在隐藏一个变量:
public Hra1()
{
// the following variable's *scope* is inside of this constructor only
// outside of the constructor, the local variable below doesn't exist.
Mince [] poleMinci = new Mince[20];
poleMinci[0] = new Mince("stříbrná", "coin.png");
poleMinci[3] = new Mince("stříbrná", "coin.png");
poleMinci[4] = new Mince("zlatá", "coin_gold.png");
poleMinci[8] = new Mince("stříbrná", "coin.png");
poleMinci[10] = new Mince("stříbrná", "coin.png");
poleMinci[12] = new Mince("stříbrná", "coin.png");
}
在该构造函数中,由于 pollMinci 是在构造函数内部声明的,因此它仅在构造函数内部可见。如果类中存在同名变量,则该变量将为 null。要解决此问题,请不要在本地重新声明变量。做:
public Hra1()
{
// Mince [] poleMinci = new Mince[20]; // **** not this ****
poleMinci = new Mince[20]; // **** but this. note the difference? ****
poleMinci[0] = new Mince("stříbrná", "coin.png");
poleMinci[3] = new Mince("stříbrná", "coin.png");
poleMinci[4] = new Mince("zlatá", "coin_gold.png");
poleMinci[8] = new Mince("stříbrná", "coin.png");
poleMinci[10] = new Mince("stříbrná", "coin.png");
poleMinci[12] = new Mince("stříbrná", "coin.png");
}
有关此问题的更多信息,请查看可变阴影 http://en.wikipedia.org/wiki/Variable_shadowing。大多数 IDE 要么会警告您可能正在执行此操作,要么有一个设置允许它们执行此操作。我使用 Eclipse 并设置了 IDE 来警告我。您可能也希望这样做。