使用for循环删除数组中的元素

时间:2014-11-25 06:48:51

标签: c#

您好我正在创建一个程序,其中包含三个数组,一个用于姓氏,一个用于得分,一个用于玩家编号,现在我已经完成了所有数组和所有操作但是当我尝试删除时一个玩家它删除整个列表而不仅仅是输入的玩家号码的信息。我不知道如何解决这个问题。

正确方向的一些指导真的很有帮助,谢谢你

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");
    }

}

}

2 个答案:

答案 0 :(得分: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,则不会循环 all - 我怀疑你的意思是循环条件为playerCount >= 0而不是playerCount > 0

但是,我不明白为什么您提供的代码会删除多个播放器的信息 - 相反,它会多次删除一个播放器的信息。您提供的代码不是您的实际代码,或者您实际上 获得您认为的结果。 (或者我当然误读了一些东西。)

答案 1 :(得分:0)

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

这里有很多不合理的事情。例如,为什么只有少于max的玩家才允许删除?

看起来您使用值-1表示不存在的播放器。在这种情况下,ProcessDelete应设置为-1而不是零。

你有一个for循环说:从我的删除索引开始,将每个数字转到ZERO,删除该播放器。你不需要for循环,只需在玩家索引上调用ProcessDelete