我试图创建一个包含3种不同选项的小游戏,但我不确定如何在代码中编写: 如果答案不是1,2或3,请继续提问,直到输入为1,2或3.
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. Eat");
Console.WriteLine("2. Drink");
Console.WriteLine("3. Play");
string answer = Console.ReadLine();
if (answer == "1")
{
Console.WriteLine("you picked number 1");
}
if (answer == "2")
{
Console.WriteLine("You picked number 2");
}
if (answer == "3")
{
Console.WriteLine("You picked number 3");
}
// if answer isn't 1,2 or 3, keep asking the question untill the input is correct.
答案 0 :(得分:2)
var answer="";
while(true)
{
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. Eat");
Console.WriteLine("2. Drink");
Console.WriteLine("3. Play");
answer = Console.ReadLine();
if (answer == "1")
{
Console.WriteLine("you picked number 1");
break;
}
if (answer == "2")
{
Console.WriteLine("You picked number 2");
break;
}
if (answer == "3")
{
Console.WriteLine("You picked number 3");
break;
}
}
或
var answer="";
while(answer!="1" && answer!="2" && answer!="3")
{
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. Eat");
Console.WriteLine("2. Drink");
Console.WriteLine("3. Play");
answer = Console.ReadLine();
if (answer == "1")
{
Console.WriteLine("you picked number 1");
}
if (answer == "2")
{
Console.WriteLine("You picked number 2");
}
if (answer == "3")
{
Console.WriteLine("You picked number 3");
}
}
或
var answer="";
var validanswers = new [] {"1","2","3"};
while(!validanswers.Contains(answer))
{
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. Eat");
Console.WriteLine("2. Drink");
Console.WriteLine("3. Play");
answer = Console.ReadLine();
if (answer == "1")
{
Console.WriteLine("you picked number 1");
}
if (answer == "2")
{
Console.WriteLine("You picked number 2");
}
if (answer == "3")
{
Console.WriteLine("You picked number 3");
}
}
答案 1 :(得分:2)
类似的东西:
string answer = String.Empty;
do
{
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. Eat");
Console.WriteLine("2. Drink");
Console.WriteLine("3. Play");
answer = Console.ReadLine();
} while (answer != "1" && answer != "2" && answer != "3");
//handle answer here