动态数组创建导致ArrayIndexOutOfBoundsException&NullPointerException
-
20-12-2019 - |
题
好吧。我觉得自己看不到这个真的很愚蠢,但我被困住了。第一个代码块与发生错误的代码的其余部分相关。提前感谢!:D
此代码确定将存在多少怪物(数组的大小)。
public static byte monsters()
{
byte b = -7; //identifies how many monsters will be found
chance = (byte)d20.nextInt(30); //dice roll
if(chance >= 24)
{
b = 4; //quadruple monsters
}
else if(chance >= 18)
{
b = 3; //triple monsters
}
else if(chance >= 12)
{
b = 2; //double monsters
}
else if(chance >= 6)
{
b = 1; //single monster
}
else
{
b = 0; //no monster
}
return b;
}//end monsters()
此代码确定并生成要放入数组的怪物。第一部分从上面的代码中获取输出以确定大小。第二部分生成怪物。当抛出"NullPointerException"时,这是它指向的代码,特别是"for(x=0;x
public void determineMons()
{
byte x = 0; //counter
switch(monsters()) //defines the array
{
case 4:
monsters = new Monster[4];
break;
case 3:
monsters = new Monster[3];
break;
case 2:
monsters = new Monster[2];
break;
case 1:
monsters = new Monster[1];
break;
}//end switch
for(x=0;x<monsters.length;x++) //populates the array
{
chance = (byte)d20.nextInt(20); //dice roll
if(chance >= 15)
{
monsters[x] = new NazRuel();
}
else if(chance >= 10)
{
monsters[x] = new GiantSnake();
}
else if(chance >= 5)
{
monsters[x] = new Yeti();
}
else
{
monsters[x] = new Zombie();
}
}//end fill For
}//end determineMons()
这里是"ArrayOutOfBoundsExceptions"代码。但是,错误在不同情况之间反弹,每次错误行都是"monster="行。
determineMons();
switch(Cell.monsters())
{
case 4:
monster = "There is a " + monsters[0] + ", a " + monsters[1] + ", a " + monsters[2] + ", and a " + monsters[3] + " in this area!";
break;
case 3:
monster = "There is a " + monsters[0] + ", a " + monsters[1] + ", and a " + monsters[2] + " in this area!";
break;
case 2:
monster = "There is a " + monsters[0] + ", and a " + monsters[1] + " in this area!";
break;
case 1:
monster = "There is a " + monsters[0] + " in this area!";
break;
}//end Monster block
解决方案
NullPointerException
如果 monsters()
返回0,变量monsters没有被交换机初始化(没有 case 0
也没有 default
)并将生成一个 NullPointerException
当你这样做的时候 monsters.length
在for循环中。
另外,你应该改变你的开关:
switch(monsters()) //defines the array
{
case 4:
monsters = new Monster[4];
break;
case 3:
monsters = new Monster[3];
break;
case 2:
monsters = new Monster[2];
break;
case 1:
monsters = new Monster[1];
break;
}
到:
int b = monsters();
if (b > 0) {
monsters = new Monsters[b];
}
这不是一个错误,但这会使你的代码更清晰。
Out of bound异常
你打电话 monsters()
两次。换句话说,您创建了数组 monsters
第一个电话 monsters()
你读了 monsters
使用对monsters()的另一个调用来确定元素的数量。
例如,假设在第一个调用 monsters()
, ,返回值为 3
.此时,您创建了一个由3个元素组成的数组。当你想打印的内容 monsters
, monsters()
申报表 4
.因此,在尝试读取第4个元素时,您将执行超出限制的错误。
作为提醒,返回的值 monsters()
是随机的:
chance = (byte)d20.nextInt(30); //dice roll
为了解决这个问题,请尝试更改:
switch(Cell.monsters())
到
switch(monsters.length)
不隶属于 StackOverflow