2013-10-27 24 views
1

我正在開發一個功能類似測驗的程序。雖然我現在遇到的問題是不允許用戶在不輸入猜測和進入下一個問題的情況下直接點擊「Enter」。 我正在嘗試兩種不同的方式,第一種方法是使用try和catch塊,但我遇到的問題是如何正確工作的。我試圖尋找彌補try和catch塊正確的語法,並試圖包括休息和繼續中,但我會得到,上面寫着「沒有封閉循環外面中斷或繼續」如何在c#中給出無效輸入後重新顯示用戶提示?

public void Play() 
    { 
     DisplayWelcome(); 

     Console.WriteLine("First Question:"); 
     Console.WriteLine("---------------"); 
     Console.WriteLine(entertainmentquestions[0]); 
     guess = Console.ReadLine(); 
     try 
     { 
      if (guess == entertainmentanswers[0]) 
      { 
       Console.WriteLine("You got it right!"); 
       Console.WriteLine("Press 'Enter' when you are ready to see the next question"); 
       Console.ReadLine(); 
       Console.Clear(); 
      } 

      else 
      { 
       Console.WriteLine("You got this one wrong! Better luck next one"); 
       Console.WriteLine("Press 'Enter' when you are ready to see the next question"); 
       Console.ReadLine(); 
       Console.Clear(); 
      } 
      break; 
     } 

     catch 
     { 
      Console.WriteLine("Incorrect input, please enter a valid answer"); 
      continue; 
     } 

的錯誤消息第二種方式,我認爲這是可以做到將通過if語句,但我不知道如何後他們按下回車鍵已經被顯示爲「無效」

public void Play() 
    { 
     DisplayWelcome(); 
     Console.WriteLine(); 
     Console.WriteLine("First Question:"); 
     Console.WriteLine("---------------"); 
     Console.WriteLine(hstryquestions[0]); 
     guess = Console.ReadLine().ToUpper(); 
     if (guess != "") 
     { 
      if (guess == hstryanswers[0]) 
      { 
       Console.WriteLine(); 
       Console.WriteLine("You got it right!"); 
       Console.WriteLine("Press 'Enter' when you are ready to see the next question"); 
       Console.ReadLine(); 
       Console.Clear(); 
      } 

      else 
      { 
       Console.WriteLine(); 
       Console.WriteLine("You got this one wrong! Better luck next one"); 
       Console.WriteLine("Press 'Enter' when you are ready to see the next question"); 
       Console.ReadLine(); 
       Console.Clear(); 
      } 
     } 
     else if (guess == "") 
     { 
      Console.WriteLine("Please enter a valid answer"); 
      Console.ReadLine(); 

     } 

任何幫助,我可以重新提示用戶將不勝感激,我很難找到這個在線和我有C#書籍的答案。也許可能是我只是不知道究竟要找什麼..

回答

1

嘗試使用循環!也許是一個do-while循環!

事情是這樣的:

do{ 
ask for input 
get input 
}while(input is not valid) 

這種循環將重複獲取用戶輸入,直到輸入通過您定義的一些有效性測試。下面是一個在C#中while循環的教程:http://www.dotnetperls.com/do

+0

對不起,我花了這麼長時間,但謝謝!這有幫助,你是非常豐富的:)。該dotnetpearls網站也是一個非常好的參考,以供將來使用,所以我很高興你在這裏包括這個 – user2908363

+0

@ user2908363很高興我可以幫助:) – AndyG

相關問題