2011-08-04 200 views
-1

有人可以找到爲什麼這個循環不工作?我是C#的新手。while循環不工作?

while (move == "r" || move == "s" || move == "f") 
      { 
       Console.Write("\nEnter your move: "); 
       move = Console.ReadLine(); 


       switch (move) 
       { 
        case "r": 
         Console.Write("\nYou have reloaded, press enter for Genius"); 
         Console.ReadLine(); 
         break; 
        case "s": 
         Console.Write("\nYou have shielded, press enter for Genius"); 
         Console.ReadLine(); 
         break; 
        case "f": 
         Console.Write("\nYou have fired, press enter for Genius"); 
         Console.ReadLine(); 
         break; 
        default: 
         Console.Write("\nInvalid move, try again\n\n"); 
         break; 
       } 


      } 
+1

「不工作」的含義是什麼?它不在循環中?它不停止?它過早退出?您是否嘗試過調試並瞭解移動的實際價值? –

+0

它不循環,但Rasel的答案工作得很好 –

回答

3

大概是因爲此舉是內環路初始化,並可能爲空或空字符串,因爲我看不到環路我假設它不是初始化之前的代碼。

我的建議是使用設置這樣

bool done = false; 
while (!done) 
{ 
    // do work 
    if (move == finalMove) // or whatever your finish condition is 
     done = true; // you could also put this as a case inside your switch 
} 
+0

不僅可以初始化,但假設它是;如果用戶輸入與r,s或f不同的東西,則while循環也會結束。如果要保留在循環中,請將默認情況設置爲您在條件中預期的值之一。 – Icarus

+0

我認爲這可能是一些邏輯,因爲如果這個人輸入一個無效的舉動,他可能希望它停止而不是報告錯誤。 –

+0

如果這是爲什麼他顯示:「無效的移動,再試一次」,而不是「哦,你是個白癡,再見!」?他應該添加一個「q」選項並退出「q」或類似的循環。 – Icarus

1

耶穌是對一個布爾標誌,建議你接受他的答案。以下是如何重寫代碼的方法。

do 
      { 
       Console.Write("\nEnter your move: "); 
       move = Console.ReadLine(); 


       switch (move) 
       { 
        case "r": 
         Console.Write("\nYou have reloaded, press enter for Genius"); 
         Console.ReadLine(); 
         break; 
        case "s": 
         Console.Write("\nYou have shielded, press enter for Genius"); 
         Console.ReadLine(); 
         break; 
        case "f": 
         Console.Write("\nYou have fired, press enter for Genius"); 
         Console.ReadLine(); 
         break; 
        default: 
         Console.Write("\nInvalid move, try again\n\n"); 
         break; 
       } 


      } 
while (move == "r" || move == "s" || move == "f"); 

不過請注意,如果你除了「R」,「S」,或「F」的東西,你將打印Invalid move, try again然後退出你的循環(他們不能再試一次)。你可能反而要分配密鑰(也許「Q」表示退出),它終止循環和改變你的while條件類似

while (move != "q"); 
+0

哦,我的意思是它其他方式,所以無效的移動啓動循環。我只需將==改爲!=,謝謝 –