簡體   English   中英

如何使用Java日歷獲取每月的第一天?

[英]How do i get the first day of the month by using java calendar?

我編寫了一個程序,該程序從用戶那里獲取說明年份和月份的輸入,並試圖打印月份。 我可以打印一個月,並且我的間隔正在工作。 但是,我沒時間工作。 該月的第一天是2018年1月,但是當我在其他年份或更晚的月份使用它時,這是不正確的。 我必須使用Java包日歷。 我在下面打印了我的代碼,我的代碼有問題嗎? 有什么辦法可以解決?

import java.util.Calendar;
import.java.util.Scanner;
public class MonthCalendar {
  public static void main(String[] args) {
    int year; // year
    int startDayOfMonth;
    int spaces;
    int month;

    //Creates a new Scanner
    Scanner scan = new Scanner(System.in);

    //Prompts user to enter year
    System.out.println("Enter a year: ");
    year = scan.nextInt();

    //Prompts user to enter month
    System.out.println("Enter the number of the month: ");
    month = scan.nextInt();


    //Calculates the 1st day of that month
    Calendar cal = Calendar.getInstance();
    cal.set(year, month - 1, 1);
    int day = cal.get(Calendar.DAY_OF_WEEK) - 1;

    // months[i] = name of month i
    String[] months = {
      " ",
      "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
    };


    // check for leap year
    if ((((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) && month == 2)
      days[month] = 29;


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

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

    // spaces required
    spaces = (days[month + 1] + day) % 7;

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

    System.out.println();

  }

正如評論中指出的那樣,您的問題不在於日期計算本身,而在於您最初設置空格的方式:

spaces = (days[month+1] + day )%7;

應該改為:

spaces = day;

您只需要知道您所在的工作日,就可以知道第一周您必須離開太空的距離。 因此,如果您在星期日,則提前0個空格,但是如果您在星期二,則希望提前2個空格,依此類推。 最終,您將增加與開始的工作日一樣多的空間,這就是day變量的含義。

看看在Ideone中為2018年2月提供正確輸出的代碼

產生以下輸出:

Enter a year: 
2018
Enter the number of the month: 
2
              February 2018
___________________________________________
  Sun   Mon   Tue   Wed   Thu   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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM