【发布时间】:2014-10-05 13:14:57
【问题描述】:
所以在这段代码中,我试图让用户输入一年和一个月(前 3 个字母),然后确定该特定月份包含多少天。由于涉及闰年的困难,我在编码用户输入“Feb”作为月份的部分时遇到了麻烦。当我测试它时,它说: “2002 年 2 月有 29 天” "2002 年 2 月有 28 天"
如何让它只显示 29 天?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a year: ");
int year= input.nextInt();
input.nextLine();
System.out.println("Enter a month (first 3 letters with the first letter in uppercase): ");
String month = input.nextLine();
// leap year logic starts here
if (year % 4 == 0 || "Feb".equals(month)) {
System.out.println( month + year + "has 29 days");
}
else if (year % 4 > 0 || "Feb".equals(month)) {
System.out.println( month + year + "has 28 days");
}
else if("Jan".equals(month) || "Mar".equals(month) ||
"May".equals(month) || "July".equals(month) ||
"Aug".equals(month) || "Oct".equals(month) ||
"Dec".equals(month)) {
System.out.println(month + year + "has 31 days");
}
else if ("Apr".equals(month)|| "Jun".equals(month) ||
"Sep".equals(month) || "Nov".equals(month)) {
System.out.println(month + year + "has 30 days");
}
【问题讨论】:
-
2002 年 2 月不是只有 28 天吗?
-
没错,我需要让它不这么说。
-
危险:每100年不是闰年,但每400年是一个。
-
对于所有没有投票权的人,我想让你知道......这实际上是几乎每个新的 Java 编码器的一个非常重要的问题。
标签: java if-statement