0
public class chocolatecake
{
    int rows,cols;
    public chocolatecake(int r, int c)
    {
        rows = r;
        cols = c;
    }
    private String letterBlock[][];

    public void fillBlock(String str)
    {
        boolean hasExtra;
        int tracker=0;
        for(int y=0;y<rows;y++)
        {
            for(int x=0;x<cols;x++)
            {
                letterBlock[y][x] = str.substring(tracker, tracker+1);
                System.out.println(letterBlock[y][x]);
                tracker++;
            }
        }
    }
}

SO the point of this program is to take a string and put it into an array first in row major order and then in column major order with a different array size, but im stuck here where the compiler is saying nullpointerexception at line 21

letterBlock[y][x] = str.substring(tracker, tracker+1);
  • Java convention is clear -- your class should be camel-cased (`ChocolateCake`). This has nothing to do with your immediate problem but it is something of which you should be aware. – eebbesen Jan 17 '15 at 02:13

3 Answers3

1

Allocate your string array in the constructor:

letterBlock = new String[r][c];

like this:

public chocolatecake(int r, int c)
{
    rows = r;
    cols = c;
    letterBlock = new String[r][c];

    // Not like this, it will create a local variable:
    // String letterBlock = new String[r][c];
}
private String letterBlock[][];

The other possible reason for a NullPointerException is if str is null. If it is not long enough you will get an IndexOutOfBoundsException.

samgak
  • 23,944
  • 4
  • 60
  • 82
1

You need to initialize the array letterBlock. e.g.

String letterBlock[][] = new String[10][2]; 
AliAvci
  • 1,127
  • 10
  • 20
0

your rows and cols are assume to be null, this in case you're not calling your chocolatecake function

roeygol
  • 4,908
  • 9
  • 51
  • 88