[英]Exceptions in Java - Try/ Catch
我正在学习 Java,我有这个程序可以根据用户编写的日期和月份来告诉符号。 该程序按原样运行,但如果用户输入 90 天左右,该程序不会评估该“错误”。 我可以通过 try/catch 来纠正这个问题吗? 如果是这样,我该怎么写? 这是代码(一部分),提前致谢
import java.util.Scanner;
public class Signo{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int day, month;
System.out.println("Day Input:");
day=in.nextInt();
System.out.println("Month Input:");
month=in.nextInt();
int result=getSign(day,month);
}
private static int getSign(int day, int month){
switch(month){
case 1:
if(month==1 && day>=20){
System.out.println("Your sign is Aquarius");
}else{
System.out.println("Your sign is Capricorn");
}
break;
//etc
}
return day;
}
}
实际上没有错误。 你要求一个整数,而用户提供的正是这个。 由您来验证它是否是您当前逻辑的有效数字。 我也会重写你的 getSign() 方法,混合开关和 if 真的没有意义。 至少在你的情况下是这样。
我会做这样的事情:
day=in.nextInt();
if(day > 30) {
while(day > 30) {
// Number is too high, feel free to spit this message out
day=in.nextInt();
}
或者甚至更好:
while(day > 30) {
day=in.nextInt();
}
你也可以提取你的day = in.nextInt();
到单个方法,如果有效/无效则返回一个布尔值
很简单,真的...
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
这就是你真正需要的。 只需将您认为可能会中断的代码放在适当的位置即可。
不过,在阅读了评论后,我同意这对您正在做的事情来说太过分了。
您只需要为 While 循环设置条件:
boolean goodAnswer = false;
while goodAnswer == false{
System.out.println("Day Input:");
day=in.nextInt();
if (day<31) { goodAnswer=true; }
}
像这样的例程将有效地继续要求一个整数,直到它得到它喜欢的一个。 只有这样它才会离开循环。 对于这类事情,这是一种相当常见的方法。
你会寻找断言/验证的东西,这通常是在方法的参数上完成的:
public void doSomething(int num) {
if (num > 30) {
throw new IllegalArgumentException("num is too high!");
}
//continue knowing that num is <= 30
}
有一些 API(如 Apache Commons)将其简化为一行:
Validate.isTrue(num <= 30, "num is too high!");
本质上与上面的代码相同,但要短得多。
所有这些都是数据验证的一部分
对此进行逻辑循环:
boolean valid = false;
while (!valid) {
try {
//take input, pass to #doSomething
valid = true;
} catch (IllegalArgumentException ex) {
//repeat / error out
}
}
//continue
尽管您可能希望使用 isValid 检查之类的东西手动验证自己:
private boolean isValidDay(int num) {
return num > 0 && num < 31;
}
//In method
Validate.isTrue(isValidDay(num), "num is not valid!");
//Without try/catch
if (isValidDay(num)) {
//call #doSomething etc
}
您根本不应该使用 try/catch。
Java 中有两种类型的异常 - 捕获/检查异常和未捕获/未检查异常(RuntimeException、Error 及其子类)。 您的情况中的异常是未捕获/未检查异常的一个示例,因为在运行时由于用户输入而发生这种情况。
大多数情况下,您不需要 try/catch 块来处理这些异常。 事实上,您甚至不需要处理这些异常。 所以你会怎么做?
您改进代码中的逻辑,以便确实发生异常。 例如,您可以使用 while 循环不断向用户询问有效数字。
if(day > 30) {
While(day > 30) {
//send message to the user
day = in.nextInt();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.