java - 程序不断抛出 ArrayIndexOutofBoundException

标签 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

最佳答案

问题是您在访问数组后进行安全检查,这使得它们毫无值(value)。要解决此问题,您需要将 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

关于java - 程序不断抛出 ArrayIndexOutofBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930707/

相关文章:

java - 需要有关基于用户角色的设计的建议

java - 如何使 SimplePanel 的边框变成虚线?

java - 我的 If 语句强制关闭

android - 在适配器中获取 ArrayIndexOutOfBoundsException

java - 如何将随机数添加到数组

java - StringIndexOutOfBoundsException 字符串索引超出范围错误

java - 如何像横版卷轴游戏那样换行?

java - Groovy 中字符串的增量运算符

java - 数组 [i] = java.lang.IndexOutOfBoundsException : Invalid array range 10 to 10

java - 收到 400 - 错误请求 Java 客户端