2015-10-22 53 views
-2

我试图用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. 
+2

你需要一个while循环 – pm100

+0

奇怪你没有找到这样做的任何例子。可能使用的搜索引擎很糟糕 - 请尝试使用[Google](https://www.google.com/?gws_rd=ssl#q=C%23+Keep+asking+untill+input+is+correct) [必应](https://www.bing.com/search?q=C%23+Keep+asking+untill+input+is+correct),然后再问问题。即使你不能立即得到答案,它也可能有助于说明你已经尝试了什么方法,以及为什么/如何不起作用。 –

回答

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 
相关问题