我正在尝试对我的程序进行错误校验,该程序基本上可以用作迷你计算器。但是我不知道如何编写“ Catch”语句来检测用户何时输入不存在的案例编号,在我的案例中为负数或> 4
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
}
}
catch(Exception e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
} ```
您还可以在default
中处理用例处理异常完全取决于您的用例,您还可以创建自定义异常并从默认值抛出类似于:
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
default:
System.out.print("Enter a correct number!")
throw new CustomException();
}
}
catch(CustomException e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
}