我的程序中的一个选项有问题,其中选项1,在将新学生添加到词典后,程序应该再次提示用户另一个选项,而是程序自动存储输入最后一个整数(添加学生的标记)并将其作为下一个选项的输入。这只发生在选项1,其他都没问题。为什么,我该怎么改变它?谢谢!
我的代码如下:
static void Main(string[] args)
{
//initialize menu
string Menu = @"1. Add a new student to the dictionary
2. Display all students in the dictionary
3. Remove an existing student from the dictionary
4. Modify an existing student's marks from the dictionary
0. Quit this program
";
//initialize student list
Dictionary<string, int> nameList = new Dictionary<string, int>();
nameList.Add("Cindy", 76);
nameList.Add("Kevin", 68);
nameList.Add("Sean", 74);
nameList.Add("Lucy", 63);
nameList.Add("Sarah", 89);
nameList.Add("Melvin", 80);
bool b = true;
while (b == true)
{
Console.Write(Menu);
Console.WriteLine();
//prompt user selection
Console.Write("Select an option: ");
int select = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Option " + select + " is selected");
Console.WriteLine();
if (select > 0)
{
switch (select)
{
case 1:
Console.Write("Enter the name of the new student: ");
string newName = Console.ReadLine();
Console.Write("Enter the marks of " + newName + ": ");
int newMark = Convert.ToInt32(Console.Read());
nameList.Add(newName,newMark);
Console.WriteLine(newName + " is added to the list");
Console.WriteLine();
break;
case 2:
Console.WriteLine("No Name Marks");
int j = 1;
foreach (KeyValuePair<string, int> kvp in nameList)
{
Console.WriteLine(j + " " + kvp.Key + " " + kvp.Value);
j++;
}
Console.WriteLine();
break;
case 3:
Console.Write("Enter the name of the student to be removed: ");
string bye = Console.ReadLine();
nameList.Remove(bye);
Console.WriteLine(bye + " has been removed from the list");
Console.WriteLine();
break;
case 4:
Console.Write("Enter the name of the student to modify marks: ");
string change = Console.ReadLine();
Console.Write("Enter the new marks for " + change + ": ");
int changemark = Convert.ToInt32(Console.ReadLine());
nameList[change] = changemark;
Console.WriteLine("Marks for " + change + " has been updated to " + changemark);
Console.WriteLine();
break;
default:
Console.WriteLine("Invalid input!");
Console.WriteLine();
break;
}
}
else if (select == 0)
{ //case 0:
Console.WriteLine("Bye!");
Console.ReadLine();
return;
}
}
}
这是上述问题的屏幕截图:
答案 0 :(得分:4)
是因为你在这里有Read()
吗?
int newMark = Convert.ToInt32(Console.Read());
而不是ReadLine()
??
int newMark = Convert.ToInt32(Console.ReadLine());
答案 1 :(得分:3)
Console.Read
(https://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx)从控制台中读取1个字符。如果你单步执行你的程序,你可能会看到Jo得到4分,而不是40分。0留在流上,并在循环的下一次迭代中被ReadLine()
选中
因此,请尝试将int newMark = Convert.ToInt32(Console.Read());
更改为int newMark = Convert.ToInt32(Console.ReadLine());