我正在尝试创建一个程序,其中CommonCharacters Student和HonorsStudent(子类到CommonCharacter)&#34;战斗&#34;通过试图让对方获得较低的测试分数。在我的主班(见下文)中,我试图模拟这个&#34;战斗&#34;在角色之间,但我无法让角色继续&#34;战斗&#34;直到除了一个以外的所有人我在while语句的条件中使用了Count属性,以便循环直到计数达到1.因为循环在3次运行后结束,所以我从来没有机会从中移除对象。 (当他们的afterScore <= 50时,荣誉学生将被删除,当他们的afterScore <= 25时,学生将被删除)。
我的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;
}
答案 0 :(得分:1)
您的while
循环以break
语句结尾。中断立即终止循环。如果你不希望你的循环终止,不要写一个break语句。
养成使用调试器逐行执行逐行代码的习惯,仔细检查每一行。养成这种习惯可以让你自己找到这样的缺陷。
我还注意到,有一个声明仅包含对Next
的调用,但会丢弃结果。这几乎肯定是错的;该方法仅对其结果有用!
这里可能存在很多错误。再次,进入调试器,逐行,,并验证每行都完全符合您的意图。由于至少有一条线没有按照你的意思去做,这就是错误。