如何在Java中显示日历[英] How to display calendar in java

问题描述

我目前正在做一个问题集,其中我必须创建一个日历,以显示一年中的所有几个月,包括其中的一个月.但是,我每月的第一行间距都有问题.在课堂上,我们只学会了开关语句,如果,否则,do-wile for loops

这是我一个月中当前显示的内容:

输出的图像 在图片中没有显示我的投入,但我写的是2016年的年份,而这一年开始的工作日为5.

输出的图像的输出图像 同样,这是一张所需的图片.我认为我的问题可能是我使用的方程式,即:int firstdayeachmonth =(daysMonth + firstdayyear)%7;尽管老师给我们使用了这个方程式,但似乎它不起作用.

您可以看到第一行的空间一直是左边的,应该与指定的日期保持一致,在这种情况下,1月1日,1月1日应在星期五和1月2日对齐,应与星期六保持一致目前在周日和星期一.

    import java.util.Scanner;

    public class DisplayCalendar
       {
        public static void main(String[] args)
        {
        //Create a new scanner 
        Scanner input = new Scanner(System.in);
        
        // Prompt user to enter year 
        System.out.print("Enter a year: ");
        int year = input.nextInt();
        
        // Prompt user to enter first day of the year
        System.out.print("Enter the weekday that the year starts: ");
        int firstDayYear = input.nextInt();
        
        // A for loop that prints out each month
        for(int month = 1; month <= 12; month++)
        {
            // Set the value of the amount of days in a month
            int daysMonth = 0;
            
            // Set value of the month 
            String monthDisplay = "";   
            
            // Find name of each month and number of days
            switch(month)
            {
                case 1: monthDisplay = "January"; 
                    daysMonth = 31;
                    break;
                
                case 2: 
                    monthDisplay = "February";
                    int leapYear = 0;
                    while (leapYear > -1)
                    {   
                        // Count all years that are divisible by 4 to be a leap year.
                        leapYear += 4;
                        
                        // If the year inputted is a leap year, the days of the month will be 29.
                        if (year == leapYear)
                        {
                            daysMonth = 29;
                            break;
                        }
                        
                        else 
                        {
                            daysMonth = 28;
                        }
                    }
                    break;

                case 3: monthDisplay = "March";
                    daysMonth = 31;
                    break;
                
                case 4: monthDisplay = "April";
                    daysMonth = 30;
                    break; 
                
                case 5: monthDisplay = "May";
                    daysMonth = 31;
                    break;
                
                case 6: monthDisplay = "June";
                    daysMonth = 30;
                    break; 
                
                case 7: monthDisplay = "July";
                    daysMonth = 31;
                    break;
                
                case 8: monthDisplay = "August";
                    daysMonth = 31;
                    break;
                
                case 9: monthDisplay = "September";
                    daysMonth = 30;
                    break;
            
                case 10: monthDisplay = "October";
                    daysMonth = 31;
                    break;
                
                case 11: monthDisplay = "November";
                    daysMonth = 30;
                    break;
                
                case 12: monthDisplay = "December";
                    daysMonth = 31;
                    break; 
                
                // If the month is not recognized, dialog box will be displayed, and then exits program. 
                default : System.out.print("Invalid: Your month is not recognized. ");
                    System.exit(0); 

            }
            // Display the month and year
            System.out.println("                      "+ monthDisplay + " " + year);
            
            // Display the lines
            System.out.println("_____________________________________");
            
            // Display the days of the week
            System.out.println("Sun     Mon     Tue     Wed     Thu     Fri     Sat");
            
            // Print spaces depending on the day the month starts.
            int firstDayEachMonth = (daysMonth + firstDayYear)%7;
            for (int space = 1; space <= firstDayEachMonth; space++)
                System.out.print("   ");

            // Print the days 
            for (int daysDisplay = 1; daysDisplay <= daysMonth; daysDisplay++)
            {
                if (firstDayYear%7 == 0)
                    System.out.println();
                
                System.out.printf("%3d      ", daysDisplay);
                firstDayYear += 1;
            }
            System.out.println();
        }
            
    }
}   

我们不能使用不同的库(例如Calendar),只与扫描仪保持一致.

推荐答案

您可以尝试此示例吗? 我可以看到以下输出:

   February 2016
   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
package general;

import java.util.Scanner;

public class DisplayCalendar {

    public static void main(String[] args) {
        int Y = 2016;    // year
        int startDayOfMonth = 5;
        int spaces = startDayOfMonth;

        // 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
            };

            for (int M = 1; M <= 12; M++) {

            // 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();
        }
    }
}

其他推荐答案

由于这似乎是一项功课,所以我不会为您提供正确的算法.那将打败您的目的 - 或其他有相同问题的人 - 练习您的编程和分析技能.

在此行中for (int space = 1; space <= firstDayEachMonth; space++)您可以完全忽略firstDayEachMonth并使用firstDayYear计数器.该柜台有一年的开始工作日,每天都会逐渐增加.另外,有必要定义您的一周是否在0或1中开始.

在这一部分中,您已经在此处设置了本周结束的线路休息:

if (firstDayYear%7 == 0)
   System.out.println();

我会重置firstDayYear当您达到此条件时,因为您将其用作参数来设置空格,因此您永远不会大于7日历和唯一的问题是在屏幕上以正确的格式显示.

当您打印一周标题的日子时,如下System.out.println("Sun Mon Tue Wed Thu Fri Sat");请注意,您的名称具有长度3加5个空间.因此,该行System.out.printf("%3d ", daysDisplay);应具有一个3个空间宽度的数字,该数字解释了%3d的使用,再加上5个空格.在这种情况下,您有6个空间,您总是会给您错误的偏移,并会在某些线上造成一些地狱.

这些是我注意到的事情,希望它有所帮助.和平!

其他推荐答案

java.Time

我建议您使用现代日期-time api *自Java SE 8.

以来一直是标准库的一部分.

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Test harness
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a month between 1 and 12 (e.g. 5): ");
        int m = input.nextInt();

        System.out.print("Please enter a full year (e.g. 2018): ");
        int y = input.nextInt();
        printMonth(y, m);
    }

    static void printMonth(int year, int month) {
        YearMonth ym = YearMonth.of(year, month);
        System.out.println("Sun Mon Tue Wed Thu Fri Sat");
        int counter = 1;

        // Get day of week of 1st date of the month and print space for as many days as
        // distant from SUN
        int dayValue = LocalDate.of(year, month, 1).getDayOfWeek().getValue();
        if (dayValue != 7)
            for (int i = 0; i < dayValue; i++, counter++) {
                System.out.printf("%-4s", "");
            }

        for (int i = 1; i <= ym.getMonth().length(ym.isLeapYear()); i++, counter++) {
            System.out.printf("%-4d", i);

            // Break the line if the value of the counter is multiple of 7
            if (counter % 7 == 0) {
                System.out.println();
            }
        }
    }
}

样本运行:

Please enter a month between 1 and 12 (e.g. 5): 9
Please enter a full year (e.g. 2018): 2020
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  

trail "> trail到:日期时间 .


*出于任何原因,如果您必须坚持使用Java 6或Java 7,则可以使用 threeten-backport backport将大部分 java.time 功能 java 6&7. Android Project和您的Android API级别仍然不符合Java-8,检查 java 8+ API可通过Desugaring 如何在Android Project中使用Threetenabp .

本文地址:https://www.itbaoku.cn/post/978388.html