在while循环中为闰年添加日期检查
问题描述:
嘿,我有这个while循环,它检查用户输入的日期的有效输入。我需要在这个while循环中添加一个检查,如果它不是闰年的一天不能超过28,并且如果它是闰年,那么不能超过29,如果month是二月,意味着month = 2。在while循环中为闰年添加日期检查
我该怎么办呢?我知道,要检查它是否是闰年,我使用以下语句:if ((year%4 == 0 && year%100 !=0) || (year%400 == 0))
。
这里是我的循环:
while ((day>31 || day<=0) || (month>12 || month<=0) || (year<=0))
{
System.out.println("The original date/month/year is invaild");
System.out.println("Please enter 3 integers to represent a valid date:");
day = scan.nextInt();
month = scan.nextInt();
year = scan.nextInt();
}
顺便说一句,我不能使用任何方法或类,这是一个家庭作业。
答
不知道这是否是你要求的,但你不需要直接推入所有的条件。你可以这样做:
boolean isDateValid = false;
while (! isDateValid) {
System.out.println("The original date/month/year is invaild");
System.out.println("Please enter 3 integers to represent a valid date:");
day = scan.nextInt();
month = scan.nextInt();
year = scan.nextInt();
isDateValid = ... that lengthy conditition
}
当然,这个心不是确切不错,因为用户首先用没有道理的错误消息映入眼帘。因此,我们可以扭转乾坤,并使用一个do/while循环,而不是:
boolean isDateValid = false;
do {
System.out.println("Please enter 3 integers to represent a valid date:");
day = scan.nextInt();
month = scan.nextInt();
year = scan.nextInt();
isDateValid = ... that lengthy conditition
if (!isDateValid) {
System.out.println("The original date/month/year is invalid; please try again");
}
} while (!isDateValid)
而对于实际的检查,只需用分离在你的心中,事情开始 - 方面都需要进行检查,像什么:
public static boolean isLeapYear(int year) {
如果年份实际上是闰年,则返回true的方法。
您可以构建大量这样的小帮手方法,用于检查不同的问题的各个方面。最后,你把这些小片放在一起做所有必要的检查。
当你说你“不能使用任何方法或类” - 大概你可以写你自己的*方法,不是吗?这就是我要做的 - 不要试图把所有东西都放在一个巨大的条件下,而是写一个'isValidDate(int year,int month,int day)'方法。 –
使用日历可以获得当月的实际最大值。 https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html –
@mrmcwolf我认为这里的一个明确部分是:他应该写他自己的日期验证。这是作业。你基本上是在告诉他作弊的一部分。 – GhostCat