数组——在java编程中制作一个月专用日历的有效方法

ki0zmccv  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(419)

我需要一些帮助;我被这种情况困扰了一段时间。我的目标是显示2021年8月的日历表单。我只需要8月份,因为我只想发布一个月的日历,供用户查看开课日期。它显示日历,但我觉得它有一种更有效的方式来编写这种类型的程序,但我不知道如何编写。你能帮帮我吗?
这是我的密码:

public class Calendar {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("\t\tMONTH OF AUGUST 2021");
        System.out.println("–––––––––––––––-------------------------––––––––––––––");
        System.out.println("\nSun\tMon\tTue\tWed\tThu\tFri\tSat\n");
        System.out.println("–––––––––––––––-------------------------––––––––––––––");
        int [][]num={{1,2,3,4,5,6,7},{8,9,10,11,12,13,14},{15,16,17,18,19,20,21},{22,23,24,25,26,27,28},{29,30,31,1,2,3,4}};

        for (int i=1; i<num.length;i++){
            for(int j=8; j<num[i].length; j++){
                num[i][j]=i+j;
            }
        }
        for(int[] a: num){
            for(int i:a){
                System.out.print(i + "\t");
            }
            System.out.println("\n");
        }
    }
}
6tdlim6h

6tdlim6h1#

要在控制台窗口中显示日历(无论哪个月),可以使用以下java方法:

public static void displayConsoleCalendar(int day, int month, int year, 
                                          boolean... useColorCodes) {
    boolean useColor = false;
    if (useColorCodes.length > 0) {
        useColor = useColorCodes[0];
    }
    String red = "\033[0;31m";
    String blue = "\033[0;34m";
    String reset = "\033[0m";
    java.util.Calendar calendar = new java.util.GregorianCalendar(year, month - 1, day + 1);
    calendar.set(java.util.Calendar.DAY_OF_MONTH, 1); //Set the day of month to 1
    int dayOfWeek = calendar.get(java.util.Calendar.DAY_OF_WEEK); //get day of week for 1st of month
    int daysInMonth = calendar.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);

    //print month name and year
    System.out.println(new java.text.SimpleDateFormat("MMMM YYYY").format(calendar.getTime()));
    System.out.println((useColor?blue:"") + " S  M  T  W  T  F  S" + (useColor?reset:""));

    //print initial spaces
    String initialSpace = "";
    for (int i = 0; i < dayOfWeek - 1; i++) {
        initialSpace += "   ";
    }
    System.out.print(initialSpace);

    //print the days of the month starting from 1
    for (int i = 0, dayOfMonth = 1; dayOfMonth <= daysInMonth; i++) {
        for (int j = ((i == 0) ? dayOfWeek - 1 : 0); j < 7 && (dayOfMonth <= daysInMonth); j++) {
            if (dayOfMonth == day && useColor) {
                System.out.printf(red + "%2d " + reset, dayOfMonth);
            }
            else {
                System.out.printf("%2d ", dayOfMonth);
            }
            dayOfMonth++;
        }
        System.out.println();
    }
}

如果您的终端支持转义颜色代码,则日历中您提供的日期将为红色。这种方法还考虑了闰年。只需提供日、月和年的整数值作为参数。应用颜色代码的最后一个参数是可选的。
如果您希望显示8月份,并希望该月份的20号以红色突出显示,则可以拨打以下电话:

displayConsoleCalendar(20, 8, 2021, true);

控制台窗口可能会显示如下内容:

klr1opcd

klr1opcd2#

要提出此解决方案(线性时间复杂度):
使用运行for循环 i 从…起 0 to 34 仅在以下情况下打印新行: i != 0 && i % 7 == 0 使用 i % 31 + 1 关于当前的数字 i 把它限制在一定范围内

public static void main(String[] args) {
    System.out.println("\t\tMONTH OF AUGUST 2021");
    System.out.println("–––––––––––––––-------------------------––––––––––––––");
    System.out.println("\nSun\tMon\tTue\tWed\tThu\tFri\tSat\n");
    System.out.println("–––––––––––––––-------------------------––––––––––––––");

    for(int i = 0; i < 35; i++) {
        if(i!= 0 && i % 7 == 0)
            System.out.println("\n");
        System.out.print(i % 31 + 1 + "\t");
    }

}

这有一个复杂而简短的版本(供好奇的人使用)

while(i < 35)
    System.out.print(
        ((i != 0 && i % 7 == 0) ? "\n": "")
        + (i++ % 31 + 1)
        + "\t"
    );
icomxhvb

icomxhvb3#

这里有一个替代方案,它实际上并不更加优雅或高效,但使用了不同的方法(不同的库),并且支持不同的语言:

public static void printCalendarFor(int month, int year, Locale locale) {
    // build the given month of the given year
    YearMonth yearMonth = YearMonth.of(year, month);
    // extract its name in the given locale
    String monthName = yearMonth.getMonth().getDisplayName(TextStyle.FULL, locale);
    // create a builder for the calendar
    StringBuilder calendarBuilder = new StringBuilder();
    // and append a header with the month name and the year
    calendarBuilder.append("\t\t    ").append(monthName).append(" ").append(year).append(System.lineSeparator());
    // then append a second header with all the days of week
    calendarBuilder.append(DayOfWeek.MONDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
                    .append(DayOfWeek.TUESDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
                    .append(DayOfWeek.WEDNESDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
                    .append(DayOfWeek.THURSDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
                    .append(DayOfWeek.FRIDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
                    .append(DayOfWeek.SATURDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
                    .append(DayOfWeek.SUNDAY.getDisplayName(TextStyle.SHORT, locale)).append(System.lineSeparator());
    // get the first day of the given month
    LocalDate dayOfMonth = yearMonth.atDay(1);

    // and go through all the days of the month handling each day
    while (!dayOfMonth.isAfter(yearMonth.atEndOfMonth())) {
        // in order to fill up the weekday table's first line, specially handle the first
        if (dayOfMonth.getDayOfMonth() == 1) {
            switch (dayOfMonth.getDayOfWeek()) {
            case MONDAY:
                calendarBuilder.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
                                .append("\t");
                break;
            case TUESDAY:
                calendarBuilder.append("\t")
                                .append(String.format("%3d", dayOfMonth.getDayOfMonth()))
                                .append("\t");
                break;
            case WEDNESDAY:
                calendarBuilder.append("\t\t")
                                .append(String.format("%3d", dayOfMonth.getDayOfMonth()))
                                .append("\t");
                break;
            case THURSDAY:
                calendarBuilder.append("\t\t\t")
                                .append(String.format("%3d", dayOfMonth.getDayOfMonth()))
                                .append("\t");
                break;
            case FRIDAY:
                calendarBuilder.append("\t\t\t\t")
                                .append(String.format("%3d", dayOfMonth.getDayOfMonth()))
                                .append("\t");
                break;
            case SATURDAY:
                calendarBuilder.append("\t\t\t\t\t")
                                .append(String.format("%3d", dayOfMonth.getDayOfMonth()))
                                .append("\t");
                break;
            case SUNDAY:
                calendarBuilder.append("\t\t\t\t\t\t")
                                .append(String.format("%3d", dayOfMonth.getDayOfMonth()))
                                .append(System.lineSeparator());
                break;
            }
        } else {
            // for all other days, just append their numbers
            calendarBuilder.append(String.format("%3d", dayOfMonth.getDayOfMonth()));
            // end the line on Sunday, otherwise append a tabulator
            if (dayOfMonth.getDayOfWeek() == DayOfWeek.SUNDAY) {
                calendarBuilder.append(System.lineSeparator());
            } else {
                calendarBuilder.append("\t");
            }
        }
        // finally increment the day of month
        dayOfMonth = dayOfMonth.plusDays(1);
    }
    // print the calender
    System.out.println(calendarBuilder.toString());
}

下面是一些使用示例

public static void main(String[] args) {
    printCalendarFor(8, 2021, Locale.ENGLISH);
}

该示例使用的输出是

August 2021
Mon Tue Wed Thu Fri Sat Sun
                          1
  2   3   4   5   6   7   8
  9  10  11  12  13  14  15
 16  17  18  19  20  21  22
 23  24  25  26  27  28  29
 30  31

相关问题