我如何使用Java日历获得一个月的第一天



我编写了一个程序,该程序正在从用户说明年度和月份的用户中获取输入,并试图打印本月。我可以打印一个月,我的间距正常。但是,我无法度过工作日。本月的第一天是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变量所包含的。

查看代码,为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 

相关内容

最新更新