2014-11-03 61 views
-1

我正在创建一个包含三个数组的程序:一个用于人的姓,一个用于得分和一个用于玩家号码。现在,我已经得到了所有的数组和完成这一切,但是当我尝试打电话给我ProcessDelete方法我不断收到继续获取IndexOutOfRange

System.IndexOutOfRangeException

任何帮助,将不胜感激

 static Int32[] ProcessDelete(Int32[] playerNumbers, ref Int32 playerCount, String[] playerLastName, Int32[] playerPoints) 
    { 
     Int32[] newArray = new Int32[playerNumbers.Length - 1]; String[] newArray2 = new String[playerLastName.Length - 1]; Int32[] newArray3 = new Int32[playerPoints.Length - 1]; 

     int index = 0; 
     int index2 = 0; 
     int index3 = 0; 
     int j = 0; 
     int k = 0; 
     int t = 0; 
     while (index < playerNumbers.Length) 
     { 
      if (index != playerCount) 
      { 
       newArray[j] = playerNumbers[index]; 
       j++; 
      } 

      index++; 
     } 

     while (index2 < playerLastName.Length) 
     { 
      if (index2 != playerCount) 
      { 
       newArray2[k] = playerLastName[index2]; 
       k++; 
      } 

      index2++; 
     } 
      while (index3 < playerLastName.Length) 
     { 
      if (index3 != playerCount) 
      { 
       newArray3[t] = playerPoints[index3]; 
       t++; 
      } 

      index3++; 
     } 
     return newArray;   
    } 

    static void DeletePlayer(Int32[] playerNumbers, String[] playerLastName, Int32[] playerPoints, ref Int32 playerCount, Int32 MAXPLAYERS) 
    { 
     int player;// Player number to delete 
     int playerindex;//index of the player number in Array 
     if (playerCount < MAXPLAYERS) 
     { 

      player = GetPositiveInteger("\nDelete Player: please enter the player's number"); 
      playerindex = GetPlayerIndex(player, playerNumbers, playerCount); 


      if (playerindex != -1) 
      { 

       { 

        Console.WriteLine("\nDelete Player: Number - {0}, Name - {1}, Points - {2}", playerNumbers[playerindex], playerLastName[playerindex], playerPoints[playerindex]); 
        Console.WriteLine("Succesfully Deleted"); 
        Console.WriteLine(); 
        ProcessDelete(playerNumbers, ref playerCount, playerLastName, playerPoints); 
       } 
      } 
      else 
       Console.WriteLine("\nDelete Player: player not found"); 
     } 
     else 
      Console.WriteLine("\nDelete Player: the roster is empty"); 
    } 

} 

}

+0

昨天有没有人问过类似的问题? – 2014-11-03 01:29:21

+2

如果您查看异常的堆栈跟踪,它会精确地告诉您发生异常的位置。如果您在调试器中运行代码,那么调试器不仅会告诉您发生异常的位置,还会让您实际查找超出范围的变量。如果一旦您确切知道发生异常的位置和方式,您仍然不知道如何解决问题,那么您可以使用具体问题更新问题,解释您遇到的具体问题。 – 2014-11-03 01:29:42

+0

如果您将'ProcessDelete'的调用注释掉,应用程序是否不会抛出错误?还有什么'player'和'playerindex'的值被生成? – 2014-11-03 01:30:32

回答

0

在你的第三个循环中你有:

newArray3[t] = playerPoints[index2]; 
k++; 

它应该是:

newArray3[t] = playerPoints[index3]; 
t++; 
+0

在同一个地方,index2正在使用,应该是index3。可能应该只有一个循环。 – 2014-11-03 01:53:42

+0

@ BenVoigt:对,使用'index2'可能是错误信息的原因,增加'k'而不是't'只会丢弃除最后一项以外的所有项目。对三个数组使用一个循环会更好,但也许一个包含三个属性的对象数组是最好的。 – Guffa 2014-11-03 02:02:03