-1

我正在尝试通过用户的输入填充一个 9x9 数组:

Field field = new Field();
int col = 1;
int row = 1;
do {
    char ch = In.readChar();
    if (ch == '-' || ch == '0') {
        col++;
    } else if (ch >= '1' && ch <= '9') {
        field.initializeCell(col - 1, row - 1, ch - '0');
        col++;
    }
    if (col > 9) {
        row++;
        col = 1;
    }
} while (row <= 9);

In.readLine();
return field;

类字段有

public int[][] cellValue = {  {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0}};

public void initializeCell(int col, int row, int value) {
    this.cellValue[col][row] = value;
}

现在这仅允许 80 个字符,例如

123456789
123456789
123456789
123456789
123456789
123456789
123456789
123456789
12345678

并添加最后一个字符会产生一个

java.lang.ArrayIndexOutOfBoundsException: 9

谁能向我解释我的错误?

4

1 回答 1

1

这是我的代码版本(以便可以对其进行编译和测试 - 我删除了对 In 的引用并替换为硬编码值“2”):

public class OffByOne {

    public static void main(String[] args) {
        Field field = new Field();
        int col = 1;
        int row = 1;
        do {
            char ch = '2';//In.readChar();
            if(ch == '-' || ch == '0') {
                col++;
            } else if(ch >= '1' && ch <= '9') {
                field.initializeCell(col - 1, row - 1, ch - '0');
                col++;
            }
            if(col > 9) {
                row++;
                col = 1;
            }
        } while(row <= 9);

        System.out.println("Done");
        //In.readLine();
        //        return field;
    }
}

public class Field {
    public int[][] cellValue = {{0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0}};


    public void initializeCell(int col, int row, int value) {
        this.cellValue[col][row] = value;
    }
}

我编译了它,它运行得很好。它没有产生任何异常。

于 2014-05-13T04:27:54.167 回答