程序不断抛出ArrayIndexOutofBoundException

时间:2015-11-26 04:37:57

标签: java indexoutofboundsexception

每当该位置到达某个点时,此代码都会继续抛出ArrayOutBoundsException 40。有时程序运行正常。

//method to get player movement around the board

public static void playerTurn(BoardSquare[] pos)
         {

          //variables to hold data
          int newLoc;
          int newBal;
          int newRoll;


         //instance of player
         Player player1 = new Player();

        //initialize
        newBal = player1.getBalance();
        newLoc = player1.getLocation();
        BoardSquare newPos;


       do{ 

        //user press a key to start the game
        System.out.println("Press enter");
        new Scanner(System.in).nextLine();

        //player new roll, location, and balance
        newRoll = roll(); //roll of the dice
        newLoc = newLoc + (newRoll - 1); //player position
        newPos = pos[newLoc]; //info about location
        newBal = newBal - newPos.getRent(); //player new balance

        //necessary to keep the game going until player balace is 0
        if(newLoc > pos.length-1)
        {
          newLoc = (pos.length-1) - newLoc;//player new loc if > 39
        }
          //prints info on screen
          System.out.println(newRoll() + " " + newLoc + " " + newBal);   


       }while (newBal > 0);//loop until player balance get to zero


       }//ends method PlayerTurn

2 个答案:

答案 0 :(得分:0)

问题是你在访问阵列后正在进行安全检查,使它们毫无价值。要解决此问题,您需要将if语句从循环结束移动到newLoc = newLoc + (newRoll - 1)newPos = pos[newLoc]之间。在访问数组之前,保证newLoc小于数组的长度。如下,

   do{ 

    //user press a key to start the game
    System.out.println("Press enter");
    new Scanner(System.in).nextLine();

    //player new roll, location, and balance
    newRoll = roll(); //roll of the dice
    newLoc = newLoc + (newRoll - 1); //player position

    //necessary to keep the game going until player balace is 0
    if(newLoc > pos.length-1)
    {
      newLoc = (pos.length-1) - newLoc;//player new loc if > 39
    }

    newPos = pos[newLoc]; //info about location
    newBal = newBal - newPos.getRent(); //player new balance

    //prints info on screen
    System.out.println(newRoll() + " " + newLoc + " " + newBal);   


   }while (newBal > 0);//loop until player balance get to zero

答案 1 :(得分:0)

我假设错误的一行是:

newPos = pos[newLoc]; //info about location

当newLoc设置为newLoc + roll时,有可能超过了pos的数组大小。这将导致ArrayOutOfBoundsException。

希望这有帮助!