Is there any way to modify a null object in an Array?

Discussion in 'Mac Programming' started by bigrell486, Apr 15, 2007.

  1. bigrell486 macrumors 6502

    bigrell486

    Joined:
    Jul 10, 2006
    Location:
    Home
    #1
    Hi. I'm trying to place an object into an array but I keep getting null pointer exceptions is there anyway around this?

    Heres the code:

    public class Board {
    Tile tile[][] ;
    int crntx = 0;
    int crnty = 0;
    int goalx;
    int goaly;

    public Board(int numRows, int numCols){
    goalx = numRows - 1;
    goaly = numCols - 1;
    Tile tile[][] = new Tile[numRows][numCols];


    public Boolean play(Tile piece){
    tile[crntx][crnty] = piece;
    toString();
    return null;

    }

    public Boolean isWinner(){
    return false;

    }

    public Boolean isDone(){
    Boolean done = false;
    return done;

    }

    public int numRows(){
    return goalx + 1;

    }

    public int numCols(){
    return goaly + 1;

    }

    public String toString(){
    for(int y = 0; y < goaly + 1; y++) {
    for(int x = 0; x < goalx + 1; x++){
    try {
    System.out.print(tile[x][y].toString()+" ");
    } catch(NullPointerException e){
    System.out.print(". ");
    }
    }
    System.out.println();
    }
    return null;

    }
    }


    Is there any way I can fix this?
     
  2. darkwing macrumors 65816

    Joined:
    Jan 6, 2004
    #2
    Your problem is in the Board constructor. You are saying "Tile tile[][] = ..." which is causing you to make a new variable named "tile" in that scope.

    Change to:

    tile = new Tile[numRows][numCols];
     

Share This Page