如何让C#控制台程序在else分支后回到输入循环?
解决C#控制台“选择你自己的冒险”程序的无效输入循环问题
你的问题核心是当前代码只执行一次输入判断流程,不管输入有效还是无效,执行完分支逻辑后都会走到最后的Console.ReadKey()然后结束程序。要实现输入无效时回到选择步骤,需要用循环把输入和判断逻辑包裹起来,直到用户输入有效选项为止。
这里用do-while循环最适合,因为它会先执行一次输入逻辑,再判断是否需要重复执行:
//Prompt user for a choice string helpGirl; do { Console.Clear(); // 可选:清屏让界面更整洁 Console.WriteLine("What Do You Say?"); Console.WriteLine("1=\"What's wrong\" \n2=\"I have to get to school\""); Console.Write("> "); // 用Write代替WriteLine,让输入和提示符在同一行 helpGirl = Console.ReadLine(); //User Helped the Girl if (helpGirl == "1") { Console.WriteLine("\nYou ask the girl what's wrong, she slowly looks up at you..."); Console.ReadKey(true); Console.WriteLine("\nThe girl slowly turns and points to the house, saying \"I left my bracelet inside that house, can you please grab it\""); break; // 输入有效,跳出循环 } //User kept going to school else if (helpGirl == "2") { Console.WriteLine("\nYou Die!"); break; // 输入有效,跳出循环 } else { Console.WriteLine("\nPlease Choose 1 or 2"); Console.WriteLine("Press any key to try again..."); Console.ReadKey(true); // 等待用户按键后重新循环 } } while (true); // 循环会一直执行,直到遇到break跳出 Console.ReadKey();
关键修改说明:
- 用
do-while(true)包裹整个输入判断流程,确保输入无效时能重复执行 - 有效选项分支里加
break,让程序执行完对应逻辑后跳出循环,继续后续流程 - 无效分支里添加等待按键的逻辑,让用户看到提示后再重新输入
- 可选的
Console.Clear()可以让每次输入的界面更干净,避免重复显示旧内容
内容的提问来源于stack exchange,提问作者Mondor
相关产品推荐
相关产品推荐

