繁体   English   中英

如果,否则,是否以及其他陈述? java的

[英]if, else if, and else statements? java

我将尽我所能清楚地表达我的问题,如果对我的问题没有任何理解,我深表歉意。我对Java还是很陌生(在我的第一个Java类中已经花了几周的时间)。

我的作业的一部分是:“修改Invoice类中的构造函数,因此根据月份,该日期不大于31、30或28。如果月份无效,因此被迫为0,则也强制天到0。”

因此,在我的原始程序中,我将其作为月和日方法:

public void setMonth(int month) {
if(month < 1 || month > 12) //if month is less than 1 and greater than 12 force number to 0
    this.month = 0;
else
    this.month = month;
}

public void setDay(int day) {
if(day < 1 || day > 31) //if day is less than 1 and greater than 31 force to 0
    this.day = 0;
else
    this.day = day;
}

因此,我想我会感到困惑的地方是,我是否应该使用“ else if”来确保日期不超过31、30或28(取决于月份)? (我也不确定Java是否支持'else if'?C ++是我最了解的内容)

喜欢:

else if(month = 2 && day > 28)
this.day = 0;

(我知道此代码不正确,当我键入它时出现了错误)。 您认为对我而言,确保一天不超过31、30或28(视月份而定)是最好的方法吗?

else if(month = 2 && day > 28)
this.day = 0;

(我知道这段代码是不正确的, 当我键入它时它有一个错误 )。 您认为对我而言,确保一天不超过31、30或28(视月份而定)是最好的方法吗?

错误不在else if部分中,而是在month = 2部分中。 您实际上是将2分配给月份,而不是进行比较。

使用month == 2 ,您的代码就可以正常工作。

我也不确定Java是否支持'else if'吗?

Java也非常支持它。

if(day < 1 || day > 31) 
    this.day = 0;
else
    this.day = day;
}

如果day < 1 || day >31条件day < 1 || day >31 day < 1 || day >31可以解决所有问题,如果不需要的话,就可以了,但是您可能需要根据业务逻辑30 days month考虑30 days month

else if(month = 2 && day > 28)
this.day = 0;

=用于分配, ==用于比较,需要使用==进行比较,

 else if(month == 2 && day > 28)
    this.day = 0;

谢谢大家!谢谢! 知道我没有在该代码中添加两个相等的符号,我感到非常傻! 很抱歉这么简单的错误!

else if (month == 2 && day > 28)
    this.day = 0;
else if (month == 4 || month == 6 || month == 9 ||  month == 11 && day > 30)
    this.day = 0;

这就是我最终要做的,并且一切正常! 非常感谢!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM