2014-09-24 74 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