2011-08-04 198 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

哦,我的意思是它其他方式,所以无效的移动启动循环。我只需将==改为!=,谢谢 –