Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException while filling an array

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

like image 886
Mgustavoxd1 Avatar asked Apr 12 '26 00:04

Mgustavoxd1


1 Answers

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

like image 112
Justin Avatar answered Apr 13 '26 14:04

Justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!