2015-11-26 62 views
1

只要位置到達某個點,此代碼就會一直拋出ArrayOutBoundsException 40。有時程序運行良好。程序不斷拋出ArrayIndexOutofBoundException

//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 

回答

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 
0

我假設在錯誤的行是:

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

有可能是你超過POS的數組大小時newLoc被設置到newLoc +卷。這會導致ArrayOutOfBoundsException。

希望這會有所幫助!