我试图设置我的程序,提示用户将值y
或n
输入到名为resetValue
的字符串中,我尝试
将值作为char r
传递。我知道代码存在一些错误,但我很好奇我的 catch
语句的错误代码应该是什么。如果用户输入 y
或 n
以外的无效值。我只是浏览了 Oracle 网站上的错误列表,但有很多错误,我不知道哪一个最适合这个问题。
// Prompts the user to reset the program from the beginning if they wish
while(true){
System.out.print("\nWould you like to enter some new numbers? Type (y) or (n): ");
resetValue = input.readLine();
try {
char r = resetValue.charAt(0);
if( r == y || r == Y ){
break;
}
else if( r == n || r == N){
reset = true;
break;
}
}
catch (ERROR STATUS HERE) {
System.out.print("Please type either (y) or (n) on the keyboard.");
}
}
最佳答案
根据 readLine
的性质,您的代码不应抛出任何异常,除非是运行时异常,例如 NullPointerException
。捕获这些内容是不可取的,因为它们表明对代码状态的某些内容遗漏了假设(例如,您的输入流已以某种方式关闭)。
省略 try/catch
block 。
接下来,如果用户输入无效选项,给他们纠正的机会。您需要做的就是放置一个 else 条件(除了修复这些字 rune 字之外)并继续循环,直到它可以在有效输入时中断。
片段:
} else {
System.out.println("Invalid input - please enter only Y or N");
}
关于java - catch语句错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858947/