2012-02-22 2 views
0

В нем говорится, что в моем массиве я перешел по индексу. Моя программа - игра с количеством голосов, которую играют 5 игроков (5 индексов). Я использовал массивы для создания классов объектов и игроков. Я дошел до пня, где моя программа врезалась во второй или третий раунд игры. Я заметил, что во время моего второго раунда индекс не обладал свойством loop: цикл подсчитывает индекс от 1 до 5 в первом цикле, а затем занимает 2-5 во втором цикле, тогда, если я даже доберусь до третьего раунда цикла , все индексы перетасовываются вокруг значения. Я не могу перейти от 1 до 5.Что означает IndexOutofRangeException?

Как каждый игрок получает 3 догадки, используйте эти 3 догадки и выходите из игры. Я взял массив объекта, который я создал для проигрывателя, создал временный массив, меньший, чем предыдущий, и указал, что для достижения текущего массива.

Я просмотрел свои ссылки в коде и нашел столько кода, сколько мог исправить, я не могу найти ошибку, вызывающую мое исключение System.IndexOutOfRangeException. Это вызвано моим угадающим игровым классом.

Вот мой GuessingGame Класс:

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.indexoutofrangeexception.aspx –

+0

В общем, 'IndexOutofRangeException' означает, что вы пытаетесь получить доступ к элементу массива с индексом больше чем _или равна длине массива. Помните: ** индексы массива начинаются с нуля, ** не один. –

ответ

1

i находится в пределах длины nPlayer не 0-4.

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

Это означает, что вы пытаетесь получить доступ к индексу больше, чем массив. В строке:

while(playedThisRound[index] == false) 

Вы не проверять границы, прежде чем использовать индекс, и ваш крах, вероятно, есть.

+0

Хорошо, проверьте границы на playThisRound.Length? – GivenPie

0

Это означает, что вы пытаетесь получить доступ к элементу в массиве с индексом выше предела массива.

+0

... или меньше нуля. – phoog

Смежные вопросы