Java中的例外 - 尝试/捕获

时间:2016-10-18 20:03:24

标签: java exception

我正在学习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;
    }
    }

4 个答案:

答案 0 :(得分:1)

实际上没有错误。你要求一个整数,用户正在提供。由您来验证它是否是您当前逻辑的有效数字。我也会重新编写你的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();提取到单个方法,如果有效/无效则返回布尔值

答案 1 :(得分:0)

非常简单,真的......

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; }
}

这样的例程将有效地继续要求一个整数,直到它得到它喜欢的整数。只有这样它才会离开循环。对于这类事情,这是一种相当常见的方法。

答案 2 :(得分:0)

你会寻找断言/验证的东西,这通常是在方法的参数上完成的:

Validate.isTrue(num <= 30, "num is too high!");

有一些API(如Apache Commons)将其简化为一行:

boolean valid = false;
while (!valid) {
    try {
        //take input, pass to #doSomething
        valid = true;
    } catch (IllegalArgumentException ex) {
        //repeat / error out
    }
}
//continue

与上面的代码完全相同,但更短。

所有这些都是Data Validation

的一部分

对此进行逻辑循环:

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
}

虽然您可能希望仅使用isValid检查手动验证自己:

[myhost ~]$ /usr/local/jdk7/bin/jstat -gcutil 9793 1000
  S0     S1     E      O      P     YGC     YGCT    FGC    FGCT     GCT
  0.00  49.57  95.93  93.32  99.48  10086  390.628   387 1005.334 1395.962
 56.99   0.00   7.42  93.32  99.48  10087  390.691   387 1005.334 1396.025
 56.99   0.00  22.19  93.32  99.49  10087  390.691   387 1005.334 1396.025
 56.99   0.00  36.28  93.32  99.49  10087  390.691   387 1005.334 1396.025
[myhost ~]$ ps -p 9793 -o etime=
 4-12:40:52

答案 3 :(得分:0)

你根本不应该使用try / catch。

Java中有两种类型的例外 - Caught / Checked Exceptions和Uncaught / Unchecked Exceptions(RuntimeException,Error及其子类)。 在您的情况下,Exception是一个Uncaught / Unchecked异常的示例,因为在运行时由于用户输入而发生这种情况。

大多数情况下,您不需要try / catch块来处理这些异常。实际上,您甚至不需要处理这些异常。那你做什么?

您改进了代码中的逻辑,以便发生异常。例如,您可以使用while循环来向用户询问有效数字。

if(day > 30) {
    While(day > 30) {
        //send message to the user 
        day = in.nextInt();    
    }
}