使用Switch语句变量继续循环

时间:2013-02-11 02:27:46

标签: java date loops printing switch-statement

我试图让这个程序在一行中连续读出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);

}

}

2 个答案:

答案 0 :(得分:0)

你需要把switch语句放在循环中 - 或者更好地把它放在你从循环调用的单独方法中。

答案 1 :(得分: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);

    }
}
}