2012-02-22 5 views
0

그것은 내 배열에서 색인 위로 갔다고합니다. 내 프로그램은 5 명의 플레이어가하는 숫자 추측 게임입니다 (5 개의 인덱스). 배열을 사용하여 객체 및 플레이어 클래스를 만들었습니다. 게임의 두 번째 또는 세 번째 라운드에서 내 프로그램이 충돌하는 그루터기에 이르렀습니다. 두 번째 라운드에서 인덱스가 루프를 수행하지 못했음을 알게되었습니다. 루프는 첫 번째 루프에서 인덱스를 1에서 5로 계산 한 다음 두 번째 루프에서 두 번째부터 다섯 번째까지 계산합니다. 그런 다음 루프의 세 번째 라운드까지 도달하면 , 모든 인덱스가 1에서 5로 갈 수 없다는 의미로 뒤섞이는 것입니다.IndexOutofRangeException은 무엇을 의미합니까?

각 플레이어는 3 가지 추측을 얻으므로 그 3 가지 추측과 게임에서 벗어납니다. 나는 플레이어를 위해 생성 한 객체의 배열을 가져 와서 이전 배열보다 작은 임시 배열을 만들고 현재 배열을 얻기 위해이를 참조했습니다.

코드에서 내 참조를 살펴본 결과 해결할 수있는 코드가 많이 발견되어 System.IndexOutOfRangeException의 원인이되는 버그를 찾을 수 없습니다. 그것은 나의 추측 게임 클래스에 의한 것입니다. 그것은 당신이 배열보다 큰 인덱스에 액세스하려고하는 것을 의미한다

using System; // only this using statement is needed here. 

namespace GuessingGame 
{ 

class GuessingGame 
{ 
    #region instance attributes 
    private const int GUESSES_ALLOWED = 3; 
    private const int NUMBER_OF_PLAYERS_TO_START = 5; 
    private const int MIN_VALUE = 1; 
    private const int MAX_VALUE = 15; 
    private Player[] players; 
    private Random randomSource; 
    #endregion 

    public GuessingGame() 
    { 
    Console.WriteLine("Starting Constructor of GuessingGame"); 
    players = new Player[NUMBER_OF_PLAYERS_TO_START]; 
    randomSource = new Random(); 

    string playerName = ""; 
    for (int index = 0; index < players.Length; index++) 
    { 
     Console.Write("What is the name for player #" 
       + (index +1) + "?\t"); 
     playerName = Console.ReadLine(); 
     players[index] = new Player(playerName, randomSource); 
     Console.Write("\n"); 
    } 
    Console.WriteLine("Ending GuessingGame Constructor"); 
    } 

    public GuessingGame(string [] playerNames) 
    { 

    Console.WriteLine("Starting Constructor of GuessingGame"); 
    players = new Player[playerNames.Length]; 
    randomSource = new Random(); 
    for (int index = 0; index < playerNames.Length; index++) 
    { 
     players[index] = new Player(playerNames[index], randomSource); 
    } 
    } 

    public void playGame() 
    { 
    int numberOfPlayersWhoHavePlayedThisRound = 0; 
    int index = 0; 

    bool[] playedThisRound = null; 
    string playerGuessEntry = ""; 
    int playerGuessValue = -1; 
    Player[] tempArray = new Player[players.Length - 1]; 
    bool roundOver = false; 

    Console.WriteLine(
      "Starting playGame - press any key to continue"); 
    //Console.Read() 

    while (roundOver == false) // Is this the right condition? 
    { 

     playedThisRound = new bool[players.Length]; 


     while (playedThisRound[index] == false) 
     { 
      do 
      { 
       Console.Write(players[index].getName() 
         + ", Enter a number between " 
         + MIN_VALUE.ToString() 
         + " and " + MAX_VALUE.ToString() 
         + " inclusive\t"); 
       playerGuessEntry = Console.ReadLine(); 
       Console.Write("\n"); 
      } 
      while (!int.TryParse(playerGuessEntry, 
         out playerGuessValue) 
        || playerGuessValue < MIN_VALUE 
        || playerGuessValue > MAX_VALUE); 
      if(playerGuessValue < MIN_VALUE || playerGuessValue > MAX_VALUE) 
      { 
       Console.Write("Invalid guess- try again"); 
      } 
      else 
      { 

       Console.WriteLine("You entered " 
         + playerGuessValue.ToString()); 

       players[index].makeAGuess(playerGuessValue); 
       playedThisRound[index] = true; 
       if (index == players.Length) 
       { 
        Console.WriteLine("End of Round"); 
        index = 0; //edit? 
        numberOfPlayersWhoHavePlayedThisRound = 0; 
       } 

      } 
      if (players[index].getGuessesUsed() == 3) 
      {//creating a temp array 
       Console.WriteLine("Guesses MAXED"); 
       tempArray = players[index].deletePlayerFromArray(players, index); 
       players = tempArray; // referencing 
       bool[] tempBooleanArray = new bool[playedThisRound.Length - 1];//reducing size of played this round array 
       Console.WriteLine("Playedthisround length: " + playedThisRound.Length + " \nThe Index: " + index.ToString()); 
       tempBooleanArray = players[index].deletePlayerBool(playedThisRound, index); 
       playedThisRound = tempBooleanArray; 
       Console.WriteLine("New Player Array Size: " + players.Length); 
       Console.WriteLine("New Boolean Array Size: " + playedThisRound.Length); 
      } 
      if (index == players.Length - 1) 
      { 
       index = 0; 
       numberOfPlayersWhoHavePlayedThisRound = 0; 
      } 
      if (players.Length == 1) 
      { 
       roundOver = true; 
      } 
      index++; 
      numberOfPlayersWhoHavePlayedThisRound++; 
     } 
      Console.WriteLine("WINNER:" + players[index].getName() + 
       "\nWins: " + players[index].getWins() + "\nArray Size: " + players.Length.ToString()); 

    }//end of while 

    Console.WriteLine("Ending playGame - " 
      + "press any key to continue"); 
    Console.Read(); 
    } 
     public bool playersAlreadyPlayed(bool[] thePlayer) 
     { 
      bool havePlayed = false; 
      for (int plays = 0; plays < thePlayer.Length; plays++) 
      { 
       if (thePlayer[plays] == false) 
       { 
        havePlayed = false; 
       } 
       else 
       { 
        havePlayed = true; 
       } 
      } 
      return havePlayed; 
     } 

    static void Main(string[] args) 
    { 
    GuessingGame newGame = new GuessingGame(); 
    newGame.playGame(); 
    } 
} 

}

그리고 여기에 플레이어 클래스

using System; 

namespace GuessingGame 
{ 

    class Player 
    { 

     private String name; 
     private int winningNumber; 
     private int guessesUsed; 
     private int wins; 
     private Random myWinningNumberSource; 

     public Player(string newName, Random random) 
     { 
     name = newName; 
     guessesUsed = 0; 
     wins = 0; 
     myWinningNumberSource = random; 
     winningNumber = myWinningNumberSource.Next(1, 16); 
     } 


     public bool makeAGuess(int guessValue) 
     { 
      bool isWinner = false;//edit 
     if (guessValue == winningNumber) 
     { 
      wins++; 

      Console.WriteLine("Congradulations, You have guessed correct number!\n"); 
      Console.WriteLine("You have a total of " + wins + " wins!"); 
      Console.WriteLine("You have " + (3 - guessesUsed) + " guesses left!\n"); 
      winningNumber = myWinningNumberSource.Next(1, 16); 
      isWinner = true; //edit 

     } 
     else 
     { 
      guessesUsed++; 

      Console.WriteLine("Oh no! You have guessed incorretly!"); 
      Console.WriteLine("You have used " + guessesUsed + " and have " + (3 - guessesUsed) + " guesses left!"); 
      Console.WriteLine("HINT: You should have guessed " + winningNumber); 
      isWinner = false; 


      if (guessesUsed > 3) 
      { 
       Console.WriteLine("Sorry you have Lost, Game Over"); 

      } 

     } 
     return isWinner; 
     } 

     public int getGuessesUsed() 
     { 
     return guessesUsed; 
     } 

     public string getName() 
     { 
     return name; 
     } 
     public int getWins() 
     { 
      return wins; 
     } 
     public Player[] getWinner(Player[] nPlayers) 
     { 
      int maxScore = 0; //edit 
      Player[] winningPlayers; 
      winningPlayers = new Player[5]; 
      for (int i = 0; i < nPlayers.Length; i++) 
      { 
       if (nPlayers[i].wins >= maxScore) 
       { 
        winningPlayers[i].wins = nPlayers[i].getWins(); 
        winningPlayers[i].name = nPlayers[i].getName(); 
       } 
      } 
      return winningPlayers; 
     } 
     public bool[] deletePlayerBool(bool[] playedThisRound, int removeIndex)//edit 
     { 
      bool[] newArray = new bool[playedThisRound.Length - 1]; 
      int tempIndex = 0; 
      for (int i = 0; i < playedThisRound.Length; i++) 
      { 
       if (i != removeIndex) 
       { 
        newArray[tempIndex++] = playedThisRound[i]; 
       } 
      } 
      return newArray; 
     } 
     public Player[] deletePlayerFromArray(Player[] nPlayers, int removeIndex) 
     { 
      Player[] newArray = new Player[nPlayers.Length - 1]; 
      int tempIndex = 0; 
      for (int i = 0; i < nPlayers.Length; i++) 
      { 
       if (i != removeIndex) 
       { 
        newArray[tempIndex++] = nPlayers[i]; 
       } 
      } 
      return newArray; 
     } 

    } 
} 
+1

여기서 디버거를 사용해야합니다. 어떤 코드 라인에서 예외가 발생합니까? –

+1

제목에 대답하려면 : http://msdn.microsoft.com/en-us/library/system.indexoutrangerange.aspx –

+0

일반적으로'IndexOutofRangeException'는 배열의 요소에 인덱스 배열의 길이보다 같거나 같습니다. ** 배열 인덱스는 0부터 시작해야합니다 **. –

답변

1

i는 0-4가 아닌 nPlayer 길이의 범위 내에 있습니다.

public Player[] getWinner(Player[] nPlayers) 
    { 
     int maxScore = 0; //edit 
     Player[] winningPlayers; 
     winningPlayers = new Player[5]; 
     for (int i = 0; i < nPlayers.Length; i++) 
     { 
      if (nPlayers[i].wins >= maxScore) 
      { 
       winningPlayers[i].wins = nPlayers[i].getWins(); 
       winningPlayers[i].name = nPlayers[i].getName(); 
      } 
     } 
     return winningPlayers; 
    } 
0

입니다 :

여기 내 GuessingGame 클래스입니다. 줄에 :

색인을 사용하기 전에 경계를 확인하지 않으므로 충돌이있을 수 있습니다.

+0

좋습니다, playsThisRound.Length에서 경계를 확인 하시겠습니까? – GivenPie

0

이는 배열의 한도보다 높은 인덱스를 가진 배열의 항목에 액세스하려고한다는 것을 의미합니다.

+0

... 또는 0보다 작습니다. – phoog

관련 문제