首页 > 解决方案 > 如何根据 Java 中的用户输入格式化日历

问题描述

我有一个任务,询问用户当月的开始日期(0 代表星期日,1 代表星期一等)。

以下是我尝试过的代码:

import java.util.Scanner;

public class CalendarMonth {

    public static void main(String[] args) {
        new CalendarMonth().runApp();
    }

    void runApp() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the start day: ");
        int startDay = in.nextInt();
        System.out.print("Enter the number of days: ");
        int daysMonth = in.nextInt();

        System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat");
        System.out.println("---\t---\t---\t---\t---\t---\t---\t");

        //determine starting day with spaces
        startDay%=7;
        //System.out.println("startDay value is " + startDay);
        for(int i = 0; i<=startDay;i++){
            System.out.print("X"); //prints a space for each empty day
        }

        for(int j = 1; j <= daysMonth; j++){
            if (j < 10){
                System.out.print(" ");
            }
            if (startDay%7 == 0){
                System.out.print( j + "\n");
            }

            else{
                System.out.print(j + "\t");
            }
            startDay++;

        }
        }

    }

这是预期的输出:

Enter the start day: 3
Enter the number of days: 30
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  29  30  

这是实际输出:

Enter the start day: 3
Enter the number of days: 30
Sun Mon Tue Wed Thu Fri Sat
--- --- --- --- --- --- --- 
XXXX 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  

日历第一行中的 XXXX 只是一个占位符,直到我弄清楚如何格式化它。我已经为此工作了很多小时,我想我需要帮助,如果慷慨的话,我可能需要一个解释。如果没有,我会尽可能多地从代码中学习。

先感谢您。

标签: javacalendar

解决方案


由于一周从 0 开始到 6 结束,因此新的一周应该在第 7 次迭代时开始一个新行,也就是 startDay 为 6 时。

我将代码更改为:

if (startDay%7 == 6){
                System.out.print( j + "\n");
            }

将 startDay 的余数除以 7,如果等于 6(即一周结束),则使代码换行。


推荐阅读