0
我想初始化一个全局二维数组,称为包含整数的正方形。变量square可能只包含值-1到8.我认为它是类似于下面的代码显示的东西,但eclipse给我一个语法错误。有没有可能的方法来做到这一点?在二维数组中允许某些值
private final int [][] square;
到
private final [-1..8] [][] square;
我想初始化一个全局二维数组,称为包含整数的正方形。变量square可能只包含值-1到8.我认为它是类似于下面的代码显示的东西,但eclipse给我一个语法错误。有没有可能的方法来做到这一点?在二维数组中允许某些值
private final int [][] square;
到
private final [-1..8] [][] square;
什么你正在寻找将值输入数组时是某种形式的验证。你也将需要某种形式的访问阵列的,如果你要设置为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");
}
}
这不是你如何声明一个数组。 –
我编辑原来的帖子,以我以前对我想做的事情。希望澄清这个问题。 –
这是不可能的。使用数据隐藏和验证来确保只能输入有效值。 – shmosel