Skip to main content
 首页 » 编程设计

C# switch 语句验证

2024年02月13日13mfrbuaa

我想知道是否有一种方法可以在 C# 中做这样的事情:

some loop here 
{ 
    Console.WriteLine("Please enter a or b"); 
    switch (Console.ReadLine().ToLower()) 
    { 
        case "a": 
            //some code here 
            break; 
        case "b": 
            //some code here 
            break; 
        default: 
            Console.WriteLine("Error, enter a or b"); 
            repeat loop 
    } 
} 

这可能是一个愚蠢的问题,但类似的问题会对我的作业大有裨益。

请您参考如下方法:

为什么不呢。运行仅在输入 a 或 b 时才存在的 while 循环。

bool condition = false; 
 
Console.WriteLine("Please enter a or b"); 
string str = string.Empty; 
while (!condition) 
{ 
     str = Console.ReadLine().ToLower(); 
     switch (str) 
     { 
         case "a": 
             //some code here 
             condition = true; 
             break; 
         case "b": 
             //some code here 
             condition = true; 
             break; 
         default: 
             Console.WriteLine("Error, enter a or b"); 
             break; 
     } 
 } 
 Console.WriteLine("You have entered {0} ", str); 
 Console.ReadLine();