2

我正在编写有关开关/案例的教程,我相信我已将程序复制到角色,但它返回的月份不正确。有人发现我的错误吗?谢谢。

导入 java.util.*;类时钟谈话{

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    //get current time and date
    Calendar now  = Calendar.getInstance();
    int hour = now.get(Calendar.HOUR_OF_DAY);
    int minute = now.get(Calendar.MINUTE);
    int month = now.get(Calendar.MONTH);
    int day = now.get(Calendar.DAY_OF_MONTH);
    int year = now.get(Calendar.YEAR);

    //display greeting
    if (hour < 12)
            System.out.println("Good moring.\n");
    else if (hour < 17)
            System.out.println("Good afternoon.\n");
    else
            System.out.println("Good evening.\n");

    //begin time message by showing the minutes
    System.out.print("It's");
    if (minute != 0) {
        System.out.print(" " + minute + " ");
        System.out.print( (minute != 1) ? "minutes" : "minute");
        System.out.print(" past");
    }

    //Display the hour
    System.out.print(" ");
    System.out.print( (hour > 12) ? (hour - 12) : hour );
    System.out.print(" o'clock on ");

    //display the name of the month
    switch (month) {
        case 1:
            System.out.print("January");
            break;
        case 2:
            System.out.print("Febuary");
            break;
        case 3:
            System.out.print("March");
            break;
        case 4:
            System.out.print("April");
            break;
        case 5:
            System.out.print("May");
            break;
        case 6:
            System.out.print("June");
            break;
        case 7:
            System.out.print("July");
            break;
        case 8:
            System.out.print("August");
            break;
        case 9:
            System.out.print("September");
            break;
        case 10:
            System.out.print("October");
            break;
        case 11:
            System.out.print("November");
            break;
        case 12:
            System.out.print("December");

    }


    //display the date and year
    System.out.println(" " + day + ", " + year + ".");



}

}

4

1 回答 1

3

Calendar.MONTH从零开始。这可能是原因。您需要添加case 0:

例子:

  case 0:
    System.out.print("January");
    break;

根据日历javadoc

公历和儒略历中的第一个月是 JANUARY,即 0;最后一个取决于一年中的月数。

于 2012-11-19T22:36:36.123 回答