我认为如果我先展示我的代码会更容易解释我的问题,所以这里是:
import java.util.Scanner;
public class a{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
System.out.print("Enter either a, b, or c: ");
try{
String a = s.nextLine();
if (!a.equalsIgnoreCase("a")&&!a.equalsIgnoreCase("b")&&!a.equalsIgnoreCase("c")){
throw new IllegalArgumentException();
}
System.out.print("Entered letter: "+a);
}
catch (IllegalArgumentException b){
System.out.println("Invalid input. Only enter a, b, or c.");
}
}
}
我的问题是,有没有办法制作三(3)个不同的 catch 语句,以便在用户输入的错误消息中指定
- 除 a、b 或 c 之外的其他字母;
- 非字母字符(数字或符号)或
- 空格?
我想到的数字错误是 NumberF
最佳答案
您可以将 catch
修改为:
try {
String a = s.nextLine();
if (!a.equalsIgnoreCase("a") && !a.equalsIgnoreCase("b") && !a.equalsIgnoreCase("c")) {
throw new IllegalArgumentException(a); // observe this
}
System.out.print("Entered letter: " + a);
} catch (IllegalArgumentException ex) {
String input = ex.getMessage();
// check for spaces
if (input.trim().length() == 0) {
System.out.println("Only black spaces entered");
}
// check for numeric/special characters
else if (input.matches("^[0-9!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]*$")) {
System.out.println("User entered a non-letter character (number or symbol)");
}
// check if it isn't a, b or c
else if ((!input.trim().matches("a|b|c"))) {
System.out.println("User entered value other than a, b or c");
}
}
观察这里:
- 我们在抛出时包含了用户输入的内容 异常
- 在
catch
block 中,我们获取用户输入的值 然后根据一些if条件打印出所需的 异常(exception)。
您可以根据自己的方便调整 catch 逻辑中的条件,我希望您了解其背后的想法。另外,您可以创建一个单独的方法来处理异常并从 catch block 中调用它。
关于Java 异常处理特异性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127288/