所以在這段代碼中,我試圖讓用戶輸入一年和一個月(前三個字母),然後確定特定月份包含多少天。由於涉及閏年的困難,我在編寫用戶輸入「Feb」爲一個月的部分時遇到了麻煩。當我測試它時,它說: 「2002年2月有29天」 「2002年2月有28天」多個If語句的閏年邏輯,如何構造它們?
如何使它只顯示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天嗎? – 2014-10-05 03:32:52
準確地說,我需要使它不會這麼說。 – blue1artic 2014-10-05 03:33:52
危險:每100年不是閏年,但每隔400年就是一年。 – eckes 2014-10-05 03:53:03