这是我所拥有的:
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int Year = input.nextInt();
System.out.print("Enter a month (first three letters with the first"
+ " letter uppercase): ");
String Month = input.next();
String ThirtyOne = "Jan" + "Mar" + "May" + "Jul" + "Aug" + "Oct" + "Dec";
String DaysThirtyOne = ThirtyOne.substring(21) + "31";
String Thirty = "Apr" + "Jun" + "Sep" + "Nov";
String DaysThirty = Thirty.substring(12) + "30";
String TwentyEight = "Feb";
String DaysTwentyEight = TwentyEight.substring(3) + "28";
String DaysLeapYear = TwentyEight.substring(3) + "29";
boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) && (Year % 400 == 0));
if (ThirtyOne.contains(Month)) {
System.out.println(Month + " " + Year + " has " + DaysThirtyOne
+ " days in it.");
}
if (Thirty.contains(Month)) {
System.out.println(Month + " " + Year + " has " + DaysThirty
+ " days in it.");
}
if(TwentyEight.contains(Month)) {
System.out.println(Month + " " + Year + " has " + DaysTwentyEight
+ " days in it.");
}
if (isLeapYear) {
System.out.println(Month + " " + Year + " has " + DaysLeapYear
+ " days in it.");
}
我是编程新手,所以如果这段代码看起来不成熟,我不会感到惊讶。无论如何,我让用户输入一年和一个月(前三个字母)。我为闰年创建了一个布尔变量,表示用户输入的任何年份都需要能被 4、100 和 400 整除。然后,我创建了一个 if 语句来判断是否是闰年,以打印出“二月(无论哪一年)用户输入)中包含 DaysLeapYear。”我认为我的算法有问题,因为如果我取出 TwentyEight 的 if 语句并只保留闰年 if 语句,计算机甚至不会打印出如果是闰年,二月会有多少天。再说一遍,我认为我的算法出了问题,但它可能在其他地方,我希望再看一下这个,看看是否有人看到了我没有看到的东西,因为我毕竟是新手。
首先,您的 isLeapYear 条件需要更改。
boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) || (Year % 400 == 0));
接下来,您的 if(TwentyEight.contains(Month)) 需要更改以考虑闰年。
if(TwentyEight.contains(Month) && !isLeapYear) {
System.out.println(Month + " " + Year + " has " + DaysTwentyEight
+ " days in it.");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)