0

我试图让这个程序在单独的一行上连续读出 1/1 到 12/31 的日期。到目前为止,我已经成功地打印了 1/1 到 1/31,但我不知道如何继续我的循环,以便它将包括其余的月/日。我知道使用日历有一种更简单的方法可以做到这一点,但我正在避开这条路线。

public class LoopDate {

public static void main(String[] args) {

    int startingDayOfWeek = 2;

    boolean isLeapYear = false;

    int month = 1;
    int year = 2000;
    int numDays = 0;
    switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        numDays = 31;
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        numDays = 30;
        break;
    case 2:
        if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
            numDays = 29;
        else
            numDays = 28;
        break;
    default:
        System.out.println("Invalid month.");
        break;
    }
    int start = 1;

    do {
        System.out.println(month + "/" + start);
        start++;
    } while (start <= numDays);

}

}
4

2 回答 2

0

您需要使用 switch 语句并将其放入循环中 - 或者甚至更好地将其放入您从循环中调用的单独方法中。

于 2013-02-11T02:31:56.663 回答
0

添加封闭循环。

public class LoopDate {

public static void main(String[] args) {

    int startingDayOfWeek = 2;

    boolean isLeapYear = false;
    int year = 2000;
    int numDays = 0;
    for(int month = 1; month <= 12;month++){
        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            numDays = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            numDays = 30;
            break;
        case 2:
            if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
                numDays = 29;
            else numDays = 28;
            break;
        default:
            System.out.println("Invalid month.");
            break;
        }
        for(int start=1;start<=numDays;start++) System.out.println(month + "/" + start);

    }
}
}
于 2013-02-11T02:32:40.887 回答