This question already has an answer here:
I have a class Hra1, which defines the rules of a game (game=hra). The problem is, that I am getting a null value, e.g. poleMinci==null, despite the array poleMinci is created in the constructor. In other words, the player's move method always returns false.
constructor:
public Hra1()
{
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");
}
player's move method:
public boolean tahHrace(Tah tah){
if (poleMinci != null){
int odkud = tah.getZPozice();
int kam = tah.getNaPozici();
boolean kamPrazdne;
if (poleMinci [kam] != null)
kamPrazdne = false;
else
kamPrazdne = true;
if (kam > odkud && poleMinci [odkud] != null && kamPrazdne == true){
poleMinci [kam] = poleMinci [odkud];
poleMinci [odkud] = null;
System.out.println("hráč táhl z pozice "+tah.getZPozice()
+ " na pozici "+tah.getNaPozici());
return true;
}
else
return false;
}
else
return false;
}
You are shadowing a variable:
In that constructor, since poleMinci was declared inside of the constructor, it is visible only inside of the constructor. If you have a variable of the same name in the class it will be null. To fix this, don't re-declare the variable locally. Do:
For more on this problem, check out Variable Shadowing. Most IDE's either will warn you that you might be doing this, or have a setting that will allow them to do this. I use Eclipse and have set my IDE to warn me. You might wish to do this too.