允许二维数组中的某些值

时间:2017-03-09 00:24:00

标签: java eclipse multidimensional-array integer

我正在尝试初始化一个名为square的全局二维数组,该数组由int组成。变量square只能包含值-1到8.我认为它类似于下面的代码,但eclipse给了我一个语法错误。有没有办法做到这一点?

private final int [][] square;

private final [-1..8] [][] square;

1 个答案:

答案 0 :(得分:0)

在数组中输入值时,您要查找的是某种形式的验证。如果要将其设置为private,您还需要对数组进行某种形式的访问,因此您可以使用public getter和setter,如下所示:

private final int [][] square = new int[10][5]; //Initialize square 2D array here.

public int getSquareValue(int x, int y)
{
    return square[x][y];
}

public void setSquareValue(int x, int y, int value)
{
    //If the value is between -1 and 8, set square[x][y] as that value. If not, then return an error message.
    if (value >= -1 && value <= 8)
    {
        square[x][y] = value;
    }
    else
    {
        System.out.println("Input value is not between -1 and 8");
    }
}