我是Java的新手,我试图使用try-catch语句。我想添加一个try catch情况,但是当我添加它时,消息只打印一次并结束。我想转载:
System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
System.out.println("Typing other numbers will end the Chatbot");
但程序刚刚结束。有没有办法循环try-catch语句?
Scanner userinput = new Scanner(System.in);
int startup;
//popup for 1 to chat, 2 to play and 3 to edit
while (true) {
try {
System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
System.out.println("Typing other numbers will end the Chatbot");
startup = userinput.nextInt();
switch (startup) {
case 1:
ConversationBot chat = new ConversationBot();
chat.ChattingBot();
break;
case 2:
GameBot game = new GameBot();
game.GamingBot();
break;
case 3:
EditBot edit = new EditBot();
edit.EditingBot();
break;
default:
System.exit(0);
}
} catch (InputMismatchException e) {
System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
break;
}
String returningCode = returnChoiceOfChatbot(startup);
System.out.println(returningCode);
}
感谢您的帮助。 BTW这是returnChoiceOf Chatbot方法
public static String returnChoiceOfChatbot(int input) {
String returnChoice = null;
switch (input) {
case 1:
returnChoice = ("You have chosen to chat with me!");
break;
case 2:
returnChoice = ("you have chsen to play word games with me!");
break;
case 3:
returnChoice = ("Please enter an input that you would give to the Chatbot.");
break;
default:
System.exit(0);
}
return returnChoice;
}//end of returnChoice method
答案 0 :(得分:2)
您需要在break;
块中将continue;
行替换为catch
。如果用户不是数字,您想要询问用户输入新内容。否则break
会中断整个while
循环并阻止它再次运行。这说,它应该是:
} catch (InputMismatchException e) {
System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
continue; // Jump back to the beginning of the while-loop
}
同时检查是否需要移动这两行:
String returningCode = returnChoiceOfChatbot(startup);
System.out.println(returningCode);
在你的while循环之外。虽然我不清楚它们的用途,看起来你可能只想在while循环离开后运行它们一次。
答案 1 :(得分:1)
break
语句(在没有标签的情况下用于指定要突破的内容)将退出最近的switch
,while
,for
或{{1} } .. do
循环。
您通常 与while
一起使用它,以阻止执行进入下一个案例 - 例如如果您没有休息并且用户选择switch
,它将执行所有三种情况的代码,然后退出程序。
但在1
阻止内,catch
退出break
循环。由于目的是告诉用户他们的输入无效然后请求新的输入,这不是你想要做的。您可以将while
更改为break
,这将中止continue
循环的当前迭代并再次启动循环,但一般来说,这种流量控制将使您的程序更难以遵循并因此维护。
当输入无效时,我猜你将最后while
放入break
代码中。但这正是异常所针对的 - 当意外发生时中止正常的代码流。所以只需移动正常流量"代码全部位于returnChoiceOfChatbot(...)
块内,您根本不需要try
(或break
):
continue
答案 2 :(得分:0)
} catch (InputMismatchException e) {
System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
break;
}
只需删除break
即可。它与catch
没有任何关系,只与你在其中写的break
有关。