This is a question about NullPointerException, what I'm tring to do is to set a symbol to every piece in my "pieces" array (the method setSymbol exists, and is a char value)
I know this is null by default, but how do I set my array, if my "set method" doesn't work?
I'm being as brief as possible with my code
Pieces[][] pzs = new Pieces[7][7];
int i, j;
for(i=0;i<8;i++){
for(j=0;j<8;j++){
pzs[i][j].setSymbol('X')
}
}
I get this exception:
Exception in thread "main" java.lang.NullPointerException
Pieces[][] pzs = new Pieces[7][7] makes a 7 by 7 array filled with nulls:
{{null,null,null,null,null,null,null},
{null,null,null,null,null,null,null},
{null,null,null,null,null,null,null},
{null,null,null,null,null,null,null},
{null,null,null,null,null,null,null},
{null,null,null,null,null,null,null},
{null,null,null,null,null,null,null}}
What you want to do is this:
Pieces[][] pzs = new Pieces[7][7];
//no need for int i, j
for(int i = 0; i < pzs.length; i++){ //pzs.length guarantees you won't get an
for(int j = 0; j < pzs[i].length; j++){ //ArrayIndexOutOfBoundsException even if pzs is something different
pzs[i][j] = new Pieces();
pzs[i][j].setSymbol('X')
}
}
Edit: Thanks to Vulpix for suggesting using pzs.length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With