gpt4 book ai didi

java - 即使不满足条件也一直抛出异常

转载 作者:行者123 更新时间:2023-12-03 23:09:16 26 4
gpt4 key购买 nike

这可能是一个非常菜鸟的问题,但我想我会在这里碰碰运气。

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

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

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

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

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

任何帮助将不胜感激,提前致谢

最佳答案

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

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

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

对于 geboortedatumboeken 也是如此。

关于java - 即使不满足条件也一直抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20997248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com