【问题标题】:Keeps throwing Exception even if it doesn't meet the condition即使不满足条件也会继续抛出异常
【发布时间】:2014-01-08 13:35:54
【问题描述】:

这可能是一个非常菜鸟的问题,但我想我会在这里抓住机会。

所以基本上我必须做一个作业,它是这样的:

我必须创建一个构造函数,但变量“naam”不能为空或空(“”),变量“geboortedatum”不能是未来,也不能是与今天相同的日期和最后一个变量“boeken”与变量“naam”具有相同的要求(不能为空或“”)。

所以我的构造器是这样的,我只能编辑这部分,因为另一部分是我们老师给的,不能编辑。

        if (this.naam == null || this.naam.equals("")) {
        throw new IllegalArgumentException("Fill in name");
    } else {
        this.naam = naam;
    }
    Date vandaag = new Date();
    if (this.geboorteDatum >= vandaag.getTime()) {
        throw new IllegalArgumentException("Date must be in the past");
    } else {
        this.geboorteDatum = geboortedatum;
    }
    if (this.boeken == null || Arrays.toString(boeken).equals("")) {
        throw new IllegalArgumentException("Can't be empty");
    } else {
        this.boeken = boeken;
    }  

它不断抛出我的第一个异常,我不知道为什么。这可能是一个非常愚蠢的问题,但我似乎无法找出原因。

任何帮助将不胜感激,在此先感谢

【问题讨论】:

    标签: java exception throw


    【解决方案1】:

    您正在测试this.naam,它是该类的实例数据成员。如果这是在你所说的构造函数中,那么除非你有一个初始化器,否则它可能是null

    您可能打算测试naam,构造函数的参数:

    if (naam == null || naam.equals("")) {
    //  ^---------------^------------------ no `this.` here
        throw new IllegalArgumentException("Fill in name");
    } else {
        this.naam = naam;
    }
    

    geboortedatumboeken 也是如此。

    【讨论】:

    • @Glenndisimo:有时我们都做过类似的事情。 :-)
    • @Glenndisimo 请注意,如果您的数组为空,Arrays.toString(boeken).equals("") 将永远不会返回 true。你应该使用boeken.length == 0
    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 2019-08-09
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    相关资源
    最近更新 更多