用Java查找闰年一个月的日子

时间:2014-10-09 17:36:04

标签: java

我正在参加java课程,我的课程必须询问月份和年份,并大喊月份中的天数。但是我被困在闰年。 这是我到目前为止所做的。

import java.util.Scanner;

public class month {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter month, 1-12: ");
        int month  = input.nextInt();
        if (month > 12)
            System.out.print("Invalid month " + month);

        else        
            System.out.print("Enter a year: ");


        int year = input.nextInt();



    switch (month * 1){
    case 1: System.out.print("January " + year); 
    System.out.print(" has 31 days."); break;
    case 2: System.out.print("February " + year); 
    System.out.print(" has 28 days."); break;
    case 3: System.out.print("March " + year); 
    System.out.print(" has 31 days."); break;
    case 4: System.out.print("April " + year);
    System.out.print(" has 30 days."); break;
    case 5: System.out.print("May " + year);
    System.out.print(" has 31 days."); break;
    case 6: System.out.print("June " + year);
    System.out.print(" has 30 days."); break;
    case 7: System.out.print("jJuly " + year);
    System.out.print(" has 31 days."); break;
    case 8: System.out.print("August " + year);
    System.out.print(" has 31 days."); break;
    case 9: System.out.print("September " + year);
    System.out.print(" has 30 days."); break;
    case 10: System.out.print("October " + year);
    System.out.print(" has 31 days."); break;
    case 11: System.out.print("November " + year);
    System.out.print(" has 30 days."); break;
    case 12: System.out.print("December " + year);
    System.out.print(" has 31 days.");
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

闰年:

case 2: System.out.print("February " + year); 
        if(isLeapYear(year)) {
            System.out.print(" has 28 days."); break;
        } else {
            System.out.print(" has 29 days."); break;
        }

// ...
public static boolean isLeapYear(int year) {
    if (year % 4 != 0) {
        return false;
    } else if (year % 400 == 0) {
        return true;
    } else if (year % 100 == 0) {
        return false;
    } else {
        return true;
    }
}