2016-04-21 83 views
3

我創建一個菜單,用戶應該輸入「1」,「2」或「3」,具體取決於他想要的選項,但如果他鍵入錯誤的東西,讓我們說「4」 ,他會收到一條錯誤消息,並會再次進入菜單。我應該在Try Catch中嵌套Do Loop嗎,還是相反?謝謝!嵌套做循環和嘗試抓住

+1

您可以使用'switch-case'! – user2004685

+1

不要對正常程序流使用try/catch。僅在特殊情況下使用它。 – Patrick

回答

0

這裏沒有必要使用循環。

您可以使用if else if或僅使用switch個案。

switch (input) { 
    case 1: 
    // menu 1; 
    break; 
    case 2: 
    // menu 2; 
    break; 
    case 3: 
    // menu 3; 
    break; 
    default: 
    // error 
    break; 
} 
1

而不是在循環中使用try-catch。您可以改用簡單的switch-case

這裏是代碼片段:

public static void main (String[] args) throws Exception { 
    Scanner in = new Scanner(System.in); 
    while(in.hasNext()) { 
     switch(in.nextInt()) { 
      case 1: System.out.println("1 Entered..."); break; 
      case 2: System.out.println("2 Entered..."); break; 
      case 3: System.out.println("3 Entered..."); break; 
      default: System.out.println("Invalid!"); 
     } 
    } 
} 

輸入:

1 
2 
5 

輸出:

1 Entered... 
2 Entered... 
Invalid! 
+1

如果進行了有效的選擇,您可能希望包括跳出循環。 – Tiz

+0

@Tiz是的,他可以在任何他想要的時候放一個'break'並離開循環。 – user2004685

1
int g =0; 
while(true) { 
    try { 
     System.out.print("Enter your guess: "); 
     g = input.nextInt(); 
     if(g<0){ 
     break; 
     } 

    } catch (Exception e) { 
     System.err.println("Not a valid input. Error :"); 
     //continue; 
    } 
} 

,如果您使用的是try catch blockwhile loop內要小心因爲在while循環的條件爲真BT的loop將繼續,所以你需要breakwhile循環,如果你使用continue;,我在我的代碼

0

有評論catch塊內,你可以繼續循環它通常是更好爲這些事情使用面向對象的方式,最值得注意的是與工廠結合的命令模式。

public interface Command { 
    String name(); 
    void execute();   
} 

public class OptionOne implements Command { 
    public String name() { 
     return "1"; 
    } 
    public void execute() { 
     System.out.println("Executing option 1"); 
    } 
} 

// command classes OptionTwo and OptionThree omitted 

public class CommandFactory { 

    private static final Command[] commands = { 
     new OptionOne(), 
     new OptionTwo(), 
     new OptioneThree() 
    }; 

    public static Command getInstance(String input) {       
     for (Command command : commands) { 
      if (command.name().equals(input)) { 
       return command 
      } 
     } 
     throw new IllegalArgumentException("no command known for input: " + input); 
    } 
} 

public class Application { 

    public static void main(String[] args) { 
     String input = args[0].trim(); 
     try { 
      CommandFactory.getInstance(input).execute(); 
     } 
     catch(IllegalArgumentException e) { 
      // logged message 
      System.err.println(e.getMessage()); 
      // message for the user 
      System.out.println("Could not handle input"); 
     }      
    } 
} 

這只是爲了表明想法。代碼未經測試。

一般來說,當您發現自己創建一個條件或開關時,您將來添加的每個用例都需要一個新的段,通常最好使用這種模式來將邏輯封裝在單獨的類。