繁体   English   中英

根据年份和年份开始日期显示日历月(Java)

[英]Display calendar month based off of the year and day the year starts (Java)

我正在编写一个代码,该代码需要用户输入年份和月份,并根据给定月份打印出特定月份的日历。 它使用循环使打印输出成为可能。

这是所需的 output

Enter a year: 2013
Enter a month (1-12): 2

                 February 2013
    ----------------------------------------
    sun  mon  tue   wed  thrus   fri   sat
                                  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   

我在网上查看了如何打印整个日历(1 月到 12 月全年)的代码,但我想知道是否有办法将整个打印输出缩短到用户选择的月份。 我确实将这个问题作为参考,并发现它很有帮助,但答案都打印了一整年。 如何在 java 中显示日历

我认为应该对该程序进行更改的是,在几个月内应该有 for 循环和部分代码确定该年是否为闰年。 我认为应该有一个用于选择月份的数组,其中任何一个都将在该部分的中间打印出来。

运行它并告诉我它是否符合您的要求:

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the year: ");
        int Y = sc.nextInt(); // year
        System.out.println();
        System.out.print("Enter the weekday the year starts on (1 for Sunday, 2 for Monday, 2 for Tuesday, etc:) ");
        int startDayOfMonth = sc.nextInt();
        int spaces = startDayOfMonth-1;
        System.out.println();

        // startDayOfMonth

        // months[i] = name of month i
        String[] months = { "", // leave empty so that we start with months[1] = "January"
                "January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
                "November", "December" };

        // days[i] = number of days in month i
        int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        
        System.out.print("Enter the month you wish to display (1 for January, 2 for February, etc) ");
        int M = sc.nextInt();
        System.out.println();
        // check for leap year
        if ((((Y % 4 == 0) && (Y % 100 != 0)) || (Y % 400 == 0)) && M == 2)
            days[M] = 29;

        // print calendar header
        // Display the month and year
        System.out.println("          " + months[M] + " " + Y);

        // Display the lines
        System.out.println("_____________________________________");
        System.out.println("   Sun  Mon Tue   Wed Thu   Fri  Sat");

        // spaces required
        spaces = (days[M - 1] + spaces) % 7;

        // print the calendar
        for (int i = 0; i < spaces; i++)
            System.out.print("     ");
        for (int i = 1; i <= days[M]; i++) {
            System.out.printf(" %3d ", i);
            if (((i + spaces) % 7 == 0) || (i == days[M]))
                System.out.println();
        }

        System.out.println();
    }
}

我从您引用的帖子中编辑了答案,以使用选择特定月份而不是遍历所有月份的扫描仪

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM