[英]Not enter in a switch case in C#
我无法输入switch语句的情况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);
}
}
我认为这是避免情况2的opc字符串存储中的“某物”。
您的问题是在do while循环开始时运行的Console.Clear
语句。 注释该行,您将看到您的代码将进入case "2"
。
即使在原始代码中,它也将变为大小写“ 2”,但是每次在do while循环开始时都会清除控制台,因此您看不到大小写“ 2”逻辑编写的语句。
您怀疑没有内存问题。
do while循环应具有Console.Clear注释,如下面的代码所示。
do {
//Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");
添加一个Console.ReadLine(); 中断情况“ 2”之前。
case "2":
Console.Clear();
for (int i = 0; i < students.Length; ++i)
{
students[i].showInfo(students[i]);
}
Console.ReadLine();
break;
您编写学生信息并在此之后调用Console.Clear()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.