我的while循环不起作用。菜单上有3个选项,用户继续输入输入,直到按下" esc"。但是在用户输入其中一个选项后程序退出,并且它不会返回菜单。如何修复while循环?请帮忙。
bool runApp = false;//menu.cs #12 Need to false sinces the loop is true
Student[] students = new Student[35];
//Application loop
while (runApp);
{
Console.Clear();
Console.WriteLine("\n\tGrade Book Menu\n");
Console.WriteLine("\t1) Add Student");
Console.WriteLine("\t2) Enter Student Grades");
Console.WriteLine("\t3) List Student Grades");
Console.Write("\nEnter Selection or Press Escape to exit: ");
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
runApp = false;
}
else
{
switch (key.Key)
{
case ConsoleKey.NumPad1:
case ConsoleKey.D1:
//Get the current student count stored in the Student Class variable
int indexForNewStudent = Student.GetStudentCount();
indexForNewStudent = 0;
Console.Write("\nEnter Student Name: ");
//Instantiate a Student object and place it in the array of Student objects called student
students[indexForNewStudent] = new Student(Console.ReadLine()); //Call overloaded constructor
//Increment Student count
Student.SetStudentCount(indexForNewStudent + 2); //Add to index to account for new student
break;
case ConsoleKey.NumPad2:
case ConsoleKey.D2:
Console.WriteLine("\nEnter the Student Number. Use List Students to get Student Number.");
int studentNumber = 0; //Temporary variable to hold the student number to enter grades
//Test the entered string is a number and between 1 and 30
if ((int.TryParse(Console.ReadLine(), out studentNumber)) && (studentNumber <= 1) &&
(studentNumber >= 30))
{
//In the event a student has not been added this code will crash
if (Student.GetStudentCount() < 0) //Has a student been added?
students[studentNumber - 1].EnterStudentScores(); //Subtract 1 from enterd number for array index
else
Console.WriteLine("A student has not been added");
}
else
{
Console.WriteLine("Invalid Student Number. Enter a number from 1 to 30");
}
break;
case ConsoleKey.NumPad3:
case ConsoleKey.D3:
Student.ListStudents(students);
break;
default:
Console.WriteLine("Invalid Menu Selection");
break;
}
Console.Write("Press a key to return to Menu");
Console.ReadKey();
}
}
Console.Write("\nExiting Application. Press any key to close window... ");
Console.ReadKey();
答案 0 :(得分:3)
你有两个问题:
“runApp”变量需要初始化为true。这允许循环运行,直到“escape”键将其设置为false。
在while(runApp)
之后删除分号。这会导致循环旋转直到条件为假(这可能是变量首先设置为false的原因)。删除它允许执行{}中的代码,直到条件变为false(在按下转义键时发生。
如果我能澄清其中的任何内容,请告诉我!
答案 1 :(得分:0)
将runApp更改为true:
bool runApp = true;
答案 2 :(得分:0)
问题出在第一行:
bool runApp = true; //this condition needs to be true or it won't enter
Student[] students = new Student[35];
//Application loop
while (runApp) //you need no ";" or it won't execute the loop
答案 3 :(得分:0)
将runApp初始化为true并通过删除分号来修复此行&#34 ;;&#34;
while (runApp);
应该是
while (runApp)