2016-01-13 20 views
1

我是Java的初學者,我想進入它,我喜歡玩它。所以我開始做一個在線課程。如何正確循環開關?

因此,在一些視頻中,我學到了一些關於switch語句的知識,並想知道如何有效地循環它們。

package v1; 

import java.util.Scanner; 

public class Computer { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     System.out.println("Computer is booting up..."); 
     System.out.println("Welcome to Mindows '93, please enter a command."); 

     String command = input.nextLine(); 
     boolean computerON = true; 

     while (computerON) { 

      switch (command) { 
      case "!music": 
       System.out.println("Playing music!"); 
       break; 
      case "!browse": 
       System.out.println("Launching browser..."); 
       break; 
      case "!help": 
       System.out.println("Here are the commands that can be used !music, !browse, !shutdown"); 
       break; 
      case "!shutdown": 
       System.out.println("Shutting down Mindows, goodbye!"); 
       break; 
      default: 
       System.out.println("Command not recognised, type !help for a list of commands..."); 
       break; 
      } 
      if (command.equals("!shutdown")) { 
       computerON = false; 
      } 
     } 
    } 
} 

所以基本上我想要的是創建一個名爲Mindows非常有限功能的模擬基於文本的操作系統,但我有問題。

當我輸入!music時,程序會不停地發送「播放音樂!

但是,當我輸入!shutdown時,它終止,這是我想要的。

我想要的是鍵入!音樂,!瀏覽,!幫助和(x)以獲得默認消息,而程序垃圾郵件行或終止。

我希望能夠不斷輸入這些命令,直到發出!shutdown命令。

回答

3

你進入無限循環,因爲你是從用戶循環之前接受輸入,輸入的執行過程中不改變循環。因此,如果您輸入「!music」,則該命令在整個循環中都不會改變,並且switch聲明在循環的每次迭代中總是進入case "!music":,這就是爲什麼computerON始終爲真,並且循環執行並打印「播放音樂」無限地。

解決這個問題的方法是在while循環內移動String command = input.nextLine();語句,就像上面的回答說的那樣。

+0

感謝您的解釋,我很感激! :) –

+0

@Scott Wilks如果你對這裏的答案滿意,請接受你最喜歡的答案/你最滿意的答案來結束這個問題。 – EvilTak

4

只讀取一次命令,不在循環中。

嘗試移動線:

String command = input.nextLine(); 

while循環。

+0

那很簡單吧?謝啦。 :) –

0

改變了你的邏輯在這裏:

boolean computerON = true; 
    while (computerON) { 
     String command = input.nextLine(); 

     switch (command) { 
     case "!music": 
      System.out.println("Playing music!"); break; 

     case "!browse": 
      System.out.println("Launching browser..."); 
      break; 

     case "!help": 
      System.out.println("Here are the commands that can be used !music, !browse, !shutdown"); 
      break; 

     case "!shutdown": 
      System.out.println("Shutting down Mindows, goodbye!"); 
      break; 

     default: 
      System.out.println("Command not recognised, type !help for a list of commands..."); 
      break; 
     } 
     if (command.equals("!shutdown")){ 
      computerON = false; 
     } 

    } 
+1

是的。你是對的 。我刪除了第二個改變。 –