Что означает IndexOutofRangeException? - PullRequest
0 голосов
/ 23 февраля 2012

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

Когда каждый игрок получает 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;
      }

   }
}

Ответы [ 3 ]

1 голос
/ 23 февраля 2012

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 голосов
/ 23 февраля 2012

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

0 голосов
/ 23 февраля 2012

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

while(playedThisRound[index] == false)

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...