我目前正在寻找此 c# 控制台应用程序功能的解决方案
我尝试寻找一种创建 while 循环的方法,该循环可以终止下面的代码,但我只得出与中断 while 循环相关的结果或不将其放入 while 循环的解决方案
int P1Choice = int.Parse(Console.ReadLine());
while (true)
{
if (P1Choice == 1)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 1");
break;
}
if (P1Choice == 2)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 2");
break;
}
if (P1Choice == 3)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 3");
break;
}
if (P1Choice == 4)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 4");
break;
}
else
{
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
int P1Choice = int.Parse(Console.ReadLine());
}
}
我知道我无法在此范围内声明本地参数“P1Choice”,但是还有其他方法可以实现代码的输出,以便当用户没有输入相应的选择时,它会再次循环?
如果您想退出while
仅当满足某些语句时才循环,那么这就是进入循环时应该声明的内容。
我会用一个boolean
了解用户是否做出了正确的选择。
bool right_choice = false;
int P1Choice = int.Parse(Console.ReadLine());
while(!right_choice) {
switch(P1Choice) {
case 1:
right_choice = true;
{case 1 code};
break;
case 2:
right_choice = true;
{case 2 code};
break;
case 3:
right_choice = true;
{case 3 code};
break;
case 4:
right_choice = true;
{case 4 code};
break;
default:
break;
}
if (!right_choice) {
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
P1Choice = int.Parse(Console.ReadLine());
}
}
}
这样,一旦用户做出正确的选择,您就退出循环。
请注意,我更改了您的代码以使用switch case
而不是 4if
s,因为这将是实现用户输入选择的可接受的方式。
祝你好运!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)