Story.direct3();
br.readLine();
Story.des();
try{
short choice1 = Short.parseShort(br.readLine());
switch(choice1){
case 1:
Display.yes();
br.readLine();
Story.rid();
String answ = br.readLine();
if ("Gravity".equals(answ) || "gravity".equals(answ)){
Display.correct();
Short choice2 = Short.parseShort(br.readLine());
switch(choice2){
case 1:
break;
}
}
else{
int less = player.hp - 10;
System.out.println("Wrong answer! Your hp will be lessen by 10. The correct answer is : 'Gravity'");
System.out.println("Your remaining HP is: " + less + "[press enter to continue...]");
br.readLine();
Story.wrong();
br.readLine();
}
break;
case 2:
Story.wrong1();
br.readLine();
break;
}
break;
}
catch(NumberFormatException ex){
System.out.println("Would you like to change your battle item?"
+ "\n[1] Yes"
+ "\n[2] No");
}
过去 2 个月我刚刚开始编写 Java 代码,并向我的 friend 询问代码并尝试对其进行实验。问题是我不知道如何放置 try/catch。我错过了什么吗?
最佳答案
当涉及到异常处理时,您应该只在 try-catch block 中放置可能导致某些异常的代码行/ block 。例如,在您的情况下,您可以 try catch 用户输入以确保他提供整数:
try{
short choice1 = Short.parseShort(br.readLine());
}catch(NumberFormatException ex){
System.out.println("Would you like to change your battle item?"
+ "\n[1] Yes"
+ "\n[2] No");
}
但这只会检查他的输入是否是数字,如果他写下 3 或 4 而你的交换机无法处理怎么办?您应该包含 switch 的默认情况或检查数字是否大于 2 或小于 1 并重复问题。
此外,这种类型的输入可以更容易地处理,而无需依赖错误处理:
String s = br.readLine();
while(!s.equals("2") || s.equals("1")){
System.out.println("Invalid input, try again:");// change message to fit your game
s = br.readLine();
}
if(s.equals("1")){
//Do something
}else{
//Do something
}
请记住,如果可以在不使代码过于复杂的情况下使用 try-catch,则应尽量避免使用。在这种情况下,您最终会得到更简单的代码。
关于java - Try/catch 我似乎不知道该把它放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832414/