2014-09-24 78 views
-2

我的项目的一个要求是,程序循环直到用户按下“X”键。我有这方法,但程序即使在未调用该方法时也会终止。这里是我的代码:即使未调用该方法,while循环也会结束[Java]

while (terminate == false) 
{ 
    // Ask user for input 

    switch (command) 
    { 
     case "I": 
     { 
      // Do stuff 
     } 

     case "X": 
     { 
      terminateProgram(); 
     } 
    } 
} 

这是我的终止方法:

private static boolean terminateProgram() 
{ 
    terminate = true; 
    return terminate; 
} 

即使我进入“I”键,循环的“I”被完成的情况下结束后。 “我”正常工作,如果terminateProgram();被评论。只有当我输入“X”时,如何才能让循环停止?

+0

对于初学者来说...你不是你从你的方法调用... – Makoto 2014-09-24 04:03:13

回答

3

您需要在每个案例声明中使用break

请阅读fall-through,这是您当前的代码正在执行的操作。

while (!terminate) 
{ 
    // Ask user for input 

    switch (command) 
    { 
     case "I": 
     { 
      // Do stuff 
      break; 
     } 

     case "X": 
     { 
      terminateProgram() 
      break; 
     } 
     default: 
      // Do something default if no condition is met. 
    } 
} 

然后在这里:

private static void terminateProgram() 
{ 
    terminate = true; // if this method simply is to terminate a program 
         // I'm not quite sure why you need a `terminate` variable 
         // unless you're using it in another part of the program. 
         // A simple system.exit(0) would suffice. 
    System.exit(0); 
} 
+2

返回并不要让终止后做与变量什么==假的,使用!terminate – DiogoSantana 2014-09-24 04:02:48

+0

当你按'X'时,'terminateProgram()'将'terminate'设置为true。你有'终止'作为一个全局变量?更好的问题 - 你在哪里宣布“终止”? (考虑学习面向对象的概念,所以你不需要静态地做所有事情)) – theGreenCabbage 2014-09-24 04:07:52

+0

实际上你的代码还有更多可以改进的地方。据我所知,你的'terminateProgram()'只是修改'terminate',所以你不需要'return'值。将'bool'改为'void'。除非你打算用'terminateProgram()'做更多,否则没有必要。简单的'terminate = true'就足以代替方法调用。 – theGreenCabbage 2014-09-24 04:09:11