使用 Switch 语句在 C# 中使用 While 循环 [英] While Loop in C# with Switch Statement
本文介绍了使用 Switch 语句在 C# 中使用 While 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果选择超出范围,我将尝试循环切换条件.但我没有得到所需的输出.因此,如果在通过 switch 条件时用户没有输入 1-3 作为输入,我希望它进入默认条件,这应该触发错误语句,然后继续循环
I am trying to loop the switch condition if the choice is out of range. But i am not getting the desired output. So if while going through the switch condition the user does not input 1-3 as input, i want it to go to default condition which should trigger the error statement and then keep looping
Console.WriteLine("Which book would you like to check out?");
Console.WriteLine("select 1 for book 1, 2 for book 2, and 3 for book 3");
int choice=Convert.ToInt32(Console.ReadLine());
bool loopBreak = true;
while (true)
{
switch (choice)
{
case 1:
Console.WriteLine("You have chosen book 1 {0}", b1.name);
b1.CheckinCheckout = false;
break;
case 2:
Console.WriteLine("You have chosen book 2 {0}", b2.name);
b2.CheckinCheckout = false;
break;
case 3:
Console.WriteLine("You have chosen book 3 {0}", b3.name);
b3.CheckinCheckout = false;
break;
default:
Console.WriteLine("Please enter a valid choice.");
loopBreak = false;
break;
}
if (loopBreak != false)
{
break;
}
}
更新:
bool loopBreak=true;
while (loopBreak==true)
{
Console.WriteLine("Which book would you like to check out?");
Console.WriteLine("select 1 for book 1, 2 for book 2, and 3 for book 3");
int choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("You have chosen book 1 {0}", b1.name);
b1.CheckinCheckout = false;
break;
case 2:
Console.WriteLine("You have chosen book 2 {0}", b2.name);
b2.CheckinCheckout = false;
break;
case 3:
Console.WriteLine("You have chosen book 3 {0}", b3.name);
b3.CheckinCheckout = false;
break;
default:
Console.WriteLine("Please enter a valid choice.");
loopBreak = false;
break;
}
break;
}
推荐答案
当你想退出循环时你需要将布尔值设置为 false,而当你想继续请求有效输入时什么都不做.
You need to set the boolean to false when you want to exit from the loop and do nothing when you want to continue asking for a valid input.
loopContinue = true;
while (loopContinue)
{
Console.WriteLine("Which book would you like to check out?");
Console.WriteLine("select 1 for book 1, 2 for book 2, and 3 for book 3");
// Use TryParse when reading the user input. This will avoid an
// Exception if the user types a letter for example.
if(Int32.TryParse(Console.ReadLine(), int out choice)
{
switch (choice)
{
case 1:
....
loopContinue = false;
break;
case 2:
....
loopContinue = false;
break;
case 3:
....
loopContinue = false;
break;
// not really needed, if you remove the default
// then your loop will not exit and you can start again
default:
loopContinue = true;
break;
}
if(loopContinue)
Console.WriteLine("Please enter a valid choice.");
}
这篇关于使用 Switch 语句在 C# 中使用 While 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文