我創建一個菜單,用戶應該輸入「1」,「2」或「3」,具體取決於他想要的選項,但如果他鍵入錯誤的東西,讓我們說「4」 ,他會收到一條錯誤消息,並會再次進入菜單。我應該在Try Catch中嵌套Do Loop嗎,還是相反?謝謝!嵌套做循環和嘗試抓住
回答
這裏沒有必要使用循環。
您可以使用if else if
或僅使用switch
個案。
switch (input) {
case 1:
// menu 1;
break;
case 2:
// menu 2;
break;
case 3:
// menu 3;
break;
default:
// error
break;
}
而不是在循環中使用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!
如果進行了有效的選擇,您可能希望包括跳出循環。 – Tiz
@Tiz是的,他可以在任何他想要的時候放一個'break'並離開循環。 – user2004685
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 block
您while loop
內要小心因爲在while循環的條件爲真BT的loop
將繼續,所以你需要break
的while
循環,如果你使用continue;
,我在我的代碼
有評論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");
}
}
}
這只是爲了表明想法。代碼未經測試。
一般來說,當您發現自己創建一個條件或開關時,您將來添加的每個用例都需要一個新的段,通常最好使用這種模式來將邏輯封裝在單獨的類。
- 1. Powershell嘗試並抓住一個循環
- 2. 在while循環中嵌套嘗試
- 3. 嘗試抓住 - 不捕捉
- 4. 嘗試在iPhone中抓住?
- 5. Sql嘗試抓住在asp.net
- 6. 嘗試和抓住TSQL - 趕不捕獲
- 7. 卡住嵌套do {for {if循環
- 8. 嘗試的foreach循環內抓
- 9. 做while循環嵌套兩個while
- 10. 如何抓住嵌套的字典
- 11. 抓住一個嵌套的跨度
- 12. 嵌套列表和循環
- 13. PHP MySQL和嵌套循環
- 14. 嵌套和打破循環
- 15. 嵌套循環求和
- 16. 嵌套循環
- 17. 嘗試抓住裏面還是外面?
- 18. 嘗試抓住最後的聲明?
- 19. 嘗試/抓住堆棧溢出在Java?
- 20. 嘗試/抓住異步任務
- 21. ASP.Net MVC嘗試抓住最佳實踐
- 22. 嘗試與抓住時調用supplyAsync
- 23. 嘗試在PHP5中抓住PDO
- 24. 嘗試抓住不捕捉異常?
- 25. 嘗試抓住沒有錯誤陳述
- 26. 嘗試/抓住移動safari中的Javascript?
- 27. Sass - 嵌套@each循環和第n個抓取單獨的值
- 28. 嵌套「for」循環是「嘗試」運營商
- 29. 試圖抓住不好的做法嗎?
- 30. 試着抓住C#我該怎麼做?
您可以使用'switch-case'! – user2004685
不要對正常程序流使用try/catch。僅在特殊情況下使用它。 – Patrick