【发布时间】:2019-03-06 05:12:12
【问题描述】:
switch 语句的 case 2 无法输入,不知道为什么。如果我删除 do while 循环,代码将完美运行。它与结构数组的内存有关吗?代码如下:
class Notebook {
struct Student
{
public String id;
public String name;
public void showInfo(Student x) {
Console.WriteLine("\t ID: " + x.id);
Console.WriteLine("\t Name: " + x.name);
}
}
static void Main(string[] args){
bool display = true;
int studentNum = int.Parse(Console.ReadLine());
Student[] students = new Student[studentNum];
do {
Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");
String opc = Console.ReadLine();
switch (opc) {
case "1":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
Console.WriteLine("Name of the student " + (i+1));
students[i].name = Console.ReadLine();
Console.WriteLine("ID of the student " + (i+1));
students[i].id = Console.ReadLine();
}
break;
case "2":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
students[i].showInfo(students[i]);
}
break;
case "3":
Console.Clear();
Console.WriteLine("bye");
display = false;
break;
}
}while(display);
}
}
我认为这是 opc 字符串内存中的“某些东西”,可以避免情况 2。
【问题讨论】:
-
您是否尝试过使用调试器?乍一看,您的代码看起来不错,但调试器可以让您查看程序流程和变量所代表的对象的详细内容。
-
只是调试。你能验证一下
opc == "2"吗? -
@vasily.sib 是的,我在设置值后写了一个 Console.WriteLine(opc) 并显示“2”,仅此而已。如果我写“3”,程序就完美结束了。
-
不,不要
Console.WriteLine(opc)。调试并检查opc == "2"是否在即时窗口中。 -
@vasily.sib 我写了 if 语句,程序跳过了它。好像没写一样。
标签: c# arrays struct switch-statement