2014-10-05 43 views
1

所以在這段代碼中,我試圖讓用戶輸入一年和一個月(前三個字母),然後確定特定月份包含多少天。由於涉及閏年的困難,我在編寫用戶輸入「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"); 
    } 
+0

2002年2月只有28天嗎? – 2014-10-05 03:32:52

+1

準確地說,我需要使它不會這麼說。 – blue1artic 2014-10-05 03:33:52

+0

危險:每100年不是閏年,但每隔400年就是一年。 – eckes 2014-10-05 03:53:03

回答

1

這只是您的條件語句中的一個簡單的邏輯缺陷。你的ORs應該是ANDs

if (year % 4 == 0 && "Feb".equals(month)){ 
    // Note the && above 
    System.out.println(month + year + "has 29 days"); 
} 
else if (year % 4 > 0 && "Feb".equals(month)){ 
    // Note the && above 
    System.out.println(month + year + "has 28 days"); 
} 

你的每個條件是(A || B)。第一個條件,年%4 == 0評估爲true,因此第二個條件甚至沒有評估(這稱爲布爾短循環)。

0

除了使用「和」(&&)你還需要嵌套他們從而彌補閏年的各種條件:

boolean feb = "Feb".equals(month); 
if (feb) { 
    if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) 
    { System.out.println("has 29 days"); } 
    else { System.out.println("has 28 days"); } 
} else if (....) { } 

我不過用數字表示的月用開關:

// NB: if you use Date.getMonth() add +1 
switch(month) { 
    case 1,3,5,7,9,10,12: 
    System.out.println("31 days"); 
    break; 
    case 4,6,7,11: 
    System.out.println("30 days"); 
    break; 
    case 2: 
    if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { 
     System.out.println("has 29 days"); 
    } else { 
     System.out.println("has 28 days"); 
    } 
    break; 
    } 

但當然,最好的閏年功能是你不編程自己的功能。更好地檢查系統庫:http://www.java2s.com/Tutorial/Java/0040__Data-Type/Getthelastdayofamonth.htm

+0

我不知道100和400的規則,謝謝! – blue1artic 2014-10-05 03:58:53

+0

我也會使用'month = input.nextLine()。toLowerCase(Locale.ENGLISH);'然後你可以使用「jan」,「feb」,「mar」作爲字符串進行比較,如果不是用戶使用大寫字母。你可以使用最後的'else {System.out.println(「未知月份」+月份); }' – eckes 2014-10-05 04:03:54

+0

謝謝你的建議!不幸的是,我正在做的任務要求使用大寫字母。 – blue1artic 2014-10-05 04:07:32