2014-11-25 234 views
0

嗨我正在创建一个程序,其中包含三个数组,一个用于人名,一个用于得分和一个用于玩家号码,现在我已经获得了所有数组和一切都完成了,但是当我尝试删除一个播放器时,它会删除整个列表,而不是仅输入播放器号码的信息。我不知道如何解决这个问题。使用for循环删除数组中的元素

在正确的方向上的一些指导,将真正帮助请和谢谢

static void ProcessDelete(Int32[] playerNumbers, ref Int32 playerCount, String[] playerLastName, Int32[] playerPoints, Int32 playerIndex) 
    { 

     playerNumbers[playerIndex] = 0; 
     playerLastName[playerIndex] = " "; 
     playerPoints[playerIndex] = 0; 

    } 



    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) 
      { 
       for (playerCount = playerindex; playerCount > 0; playerCount--) 
       { 

        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, playerindex); 
       } 
      } 
      else 
       Console.WriteLine("\nDelete Player: player not found"); 
     } 
     else 
      Console.WriteLine("\nDelete Player: the roster is empty"); 
    } 

} 

}

+0

我认为你必须揭示ProcessDelete方法的问题可能在哪里,另一方面数组不适合删除。考虑一下其他收藏,如列表。 – t3chb0t 2014-11-25 06:57:42

回答

3

我强烈建议你完全重新审视你的设计:

  • Avoid multiple "parallel" collections这样。取而代之的是,有一个收集Player类型,其中Player是一类新组成的球员号码,姓氏和得分
  • 使用List<T>,而不是阵列的 - 事实上,阵列具有固定的大小,使一很多操作与他们很难。如果你想“删除一个条目”,你需要创建一个新的数组,并将旧数组中仍然需要的所有元素复制到新数组中。这是一个痛苦。在你的代码中,你根本不是真的删除一个元素 - 你只是将得分,名字和数字设置为默认值。使用List<T>您实际上可以移除该元素。

现在你当前的代码也相当混乱这里:

for (playerCount = playerindex; playerCount > 0; playerCount--) 
{ 
    ... 
    ProcessDelete(...); 
} 

你为什么要循环呢?你已经制定了你想要“删除”的索引 - 那么为什么不只是拨打ProcessDelete一次?

// Removed the playerCount parameter. Why is it there at all? 
ProcessDelete(playerNumbers, playerLastName, playerPoints, playerindex); 

而且,如果playerIndex是0,你不会在循环所有 - 我怀疑你的意思是循环条件为playerCount >= 0而非playerCount > 0

但是,我看不出为什么您提供的代码会删除多个玩家的信息 - 相反,它会多次删除一个玩家的信息。您提交的代码不是您的实际代码,或者您不是实际上是获得您认为自己的结果。 (或者我误解了一些东西,当然。)

0

首先,如果将这三个值放入一个名为PlayerDetails的类中,然后拥有该类的单个列表,您会发现它更容易。

有很多事情在这里没有意义。例如,为什么只有在少于最大玩家的情况下才允许删除?

它看起来像你使用值-1来表示一个不存在的球员。在这种情况下,ProcessDelete应该设置为-1而不是零。

你有一个for循环说:开始在我的删除索引,通过每个数字去零,删除该播放器。你不需要for循环,只需在你的播放器索引上调用ProcessDelete

相关问题