2014-11-05 122 views
-2

所以我有一个简单的类叫Date有3个数据成员和一个单独的类Driver;并且我试图在我的设置类Date的方法中用try-catch块错误地检查输入。使用try-catch块的问题

public void setDate(int month, int day, int year) 
{ 
    try 
    { 
     dMonth = month; 
     dDay = day; 
     dYear = year; 
    } 
    catch (InputMismatchException imeR) 
    { 
     System.out.println("Wrong input type"); 
    } 
} 

但是,当我编译类Drive ...

public class Driver 
{ 
    public static void main (String[] args) 
    { 
     Date zeroDate = new Date(); 

     System.out.println(zeroDate.getMonth()); 
     zeroDate.setDate(4,4,4); 
     System.out.println(zeroDate.getMonth()); 
     zeroDate.setDate(4,4,"string"); 
    } 
} 

...,我得到以下错误:

Driver.java:14: error: incompatible types: String cannot be converted to int 
     zeroDate.setDate(4,4,"ted"); 

其他一切工作正常,当我发表评论出线...

zeroDate.setDate(4,4,"string"); 

...,我可以操纵类日期就好了。

这是我第一次尝试try-catch块。有人可以解释我缺少的东西吗?

在你的setDate方法
+0

Java不会自动将'String'转换为'int'。你必须使用一种方法来做到这一点。在'Integer'类中有一些方法可以为你做到这一点。类文档位于[此链接](http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html)。还要注意,调用你的解析方法的方法是你必须放置catch的方法。 'setDate'只是移动'int'而不做任何解析,所以把'catch'块放在那里是错误的。 – ajb 2014-11-05 02:02:35

回答

3

这不是在try-catch块。这是因为你传递了一个字符串,其中int是预期的。 由于Java是静态类型的,因此它不会让您在编译时执行此操作。

+3

为了展开,'try ... catch'语句只会捕获运行时错误。正如你所说,类型检查是在编译时完成的 – 2014-11-05 01:40:24