2015-10-22 48 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 
相關問題