基本的java算法给我一个nullpointerexception错误?

时间:2015-01-17 01:57:41

标签: java algorithm routes

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++;
            }
        }
    }
}

所以这个程序的重点是取一个字符串,然后按行主要顺序将它放入一个数组,然后以不同的数组大小的列主要顺序放入数组,但是我发现这里编译器在第21行说的是nullpointerexception

letterBlock[y][x] = str.substring(tracker, tracker+1);

3 个答案:

答案 0 :(得分:1)

在构造函数中分配字符串数组:

letterBlock = new String[r][c];
像这样:

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[][];

NullPointerException的另一个可能原因是str为null。如果时间不够长,您将获得IndexOutOfBoundsException。

答案 1 :(得分:1)

您需要初始化数组letterBlock。 e.g。

String letterBlock[][] = new String[10][2]; 

答案 2 :(得分:0)

您的rowscols假设为空,以防您未调用chocolatecake函数