【发布时间】:2016-02-08 22:43:13
【问题描述】:
我正在尝试创建一个程序,其中 CommonCharacters Student 和 HonorsStudent(CommonCharacter 的子类)通过试图让彼此获得较低的测试分数来相互“战斗”。在我的主班(见下文)中,我试图模拟角色之间的这种“战斗”,但我无法让角色继续“战斗”,直到剩下一个人。我在 while 语句的条件中使用了 Count 属性,以便它循环直到计数达到 1。因为循环在 3 次运行后结束,所以我永远没有机会从 . (HonorsStudents 在 afterScore
我的 while 循环有问题吗?
class Program
{
static void Main(string[] args)
{
List<CommonCharacter> characters = new List<CommonCharacter>();
characters.Add(new Student("Sarah", "female", 1));
characters.Add(new Student("Kevin", "male", 2));
characters.Add(new HonorsStudent("Matthew", "male", 3));
characters.Add(new HonorsStudent("Gwen", "female", 4));
// This will be used to choose a character to "battle" at random from the List of characters
Random random = new Random();
while(characters.Count > 1)
{
foreach(CommonCharacter CommonCharacter in characters)
{
int randomStudent = random.Next(characters.Count);
// This makes sure there is no instance where a student "attacks" themself
if (CommonCharacter.Name == characters[randomStudent].Name)
{
random.Next(characters.Count);
}
else
{
int points = CommonCharacter.TakeTest();
if (points > 0)
{
int afterScore = 100 - points;
Console.WriteLine(CommonCharacter.Name + " reports " + characters[randomStudent].Name + " for cheating and loses them " + points + " points.");
Console.WriteLine(characters[randomStudent].Name + " now has a test score of " + afterScore);
Console.WriteLine();
}
else if (points == 0)
{
Console.WriteLine(CommonCharacter.Name + " reports " + characters[randomStudent].Name + " for cheating but the claim is dismissed.");
Console.WriteLine();
}
}
}
// This loop checks if any Students have fled
for (int i = 0; i < 2; i++)
{
if (characters[i].HasLeftClassroom() == true && characters[i].Position == "student")
{
characters.RemoveAt(i);
Console.WriteLine(characters[i].Name + " has received below a 25 and has left the classroom.");
}
}
// This loop checks if any HonorsStudents have fled
for (int i = 2; i < 4; i++)
{
if (characters[i].HasLeftClassroom() == true && characters[i].Position == "honors student")
{
characters.RemoveAt(i);
Console.WriteLine(characters[i].Name + " has received below a 50 and has left the classroom.");
}
}
break;
}
【问题讨论】:
-
你有没有在 while 循环的开头放一个断点,跑了几行看看发生了什么?
-
@Tdorno,是的。我把它放在开头并逐步完成整个程序。 Count 属性在整个程序中读取为“4”。 (这并不让我感到惊讶,因为他们都没有达到迫使他们逃离的分数)。但它会在 4 次“战斗”后停止。
-
在我看来,它实际上可能永远不会结束。
-
@DavidG 是的,哎呀。我摆弄了一会儿,忘了撤消它的删除。
-
尽管我们正在审查这段代码,但我注意到
if (x == true)模式是新手程序员的常见标志。这意味着“如果 x 是真的”,这是说“如果 x 是真的”的一种不必要的复杂方式。如果 x 是bool,则只需if(x)即可。
标签: c# list while-loop parent-child