我有类Mappa和子类MappaFermi与数组属性Sector扇区,数组的每个单元格都应该有一个名称,在类构造函数的代码中我没有任何问题命名它们(所有测试都是成功的),但是在子类构造函数中,我在尝试运行NotNull断言时得到ArrayIndexOutOfBoundsException:14。我将数组设置为protected,以便我可以在子类中使用它。
public class Mappa {
private Name mappaName;
protected Sector [][] sector;
private int Matrix [][];
private static final int X=23;
private static final int Y=14;
public Mappa (Name mappaName){
this.mappaName=mappaName;
sector = new Settore[X][Y];
for (int i=0; i < X; i++){
for (int j=0; j<Y; j++) {
sector[i][j] = new Settore (i,j);
}
}
Matrix = new int[23][14];
if(mappaName==Name.FERMI){
sector[10][8]=new Alieni(10,8);
sector[10][9]=new Umani(10,9);
}
if(mappaName==Name.GALILEI||mappaName==Name.GALVANI){
sector[10][5]=new Alieni(10,5);//i have run all tests and it was successful
sector[10][7]=new Umani(10,7);
}
}
}
public class MappaFermi extends Mappa {
public MappaFermi() {
super(null);
new Mappa(Name.FERMI);
setMatrix(new int[][]{
{0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,2,1,2,1,2,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,1,2,2,2,1,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,3,0,1,0,3,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,2,1,0,1,0,2,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0,1,2,1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,2,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,2,1,0,1,0,2,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,2,0,1,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}});
for (int i=0; i < 14; i++){
for (int j=0; j<23; j++){
if (getMatrix()[i][j]==1){
sector[i][j]=new Sicuro(i,j);//this is where i get the error, if i only write `new Sicuro(i,j);` it runs successfully but i'm not storing the value in the cell of the array
}
else {
if (getMatrix()[i][j]==2){
sector[i][j]=new Pericoloso(i,j);
}
else {
if (getMatrix()[i][j]==3){
sector[i][j]=new Scialuppa(i,j);
}
}
}
}
}
}
}
public class MappaFermiTest {
@Test
public void testMappaFermi() {
Mappa mappa = new MappaFermi();
assertNotNull(mappa);
}
}
答案 0 :(得分:0)
扇区的维度为[23][14]
,但您尝试使用迭代[i in (0..14)]``[j in (0..23)]
对其进行初始化。您应该像这样初始化它:sector = new Settore[Y][X];
或反X和Y值。
答案 1 :(得分:0)
反转下面的循环语句
for (int i=0; i < 14; i++){
for (int j=0; j<23; j++){
带
for (int i=0; i < 23; i++){
for (int j=0; j<14; j++){
由于数组扇区的维度为[23][14];
,即23 Rows and 14 Columns
。这就是为什么你需要分别遍历所有行及其列