動的配列の作成により 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()
このコードは、配列に配置するモンスターを決定および生成します。最初の部分では、上記のコードからの出力を取得してサイズを決定します。2 番目の部分ではモンスターが生成されます。「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 を返す場合、変数モンスターはスイッチによって初期化されません ( 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];
}
これはバグではありませんが、コードがより明確になります。
範囲外の例外
あなたが呼ぶ monsters()
2回。つまり、配列を作成します 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)