簡體   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