【问题标题】:How to display calendar in java如何在java中显示日历
【发布时间】:2016-02-28 07:17:03
【问题描述】:

我目前正在做一个问题集,我必须创建一个日历来显示一年中的所有月份,包括其中的日期。但是,我对每个月第一行的间距有疑问。在课堂上我们只学习了 switch 语句,if、else、while、do-while、for 循环

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

Image of output 图片中没有显示我的输入,但我写的是 2016 年和 5 年开始的工作日。

Image of output of what what is desired 再一次,一张想要的照片。我认为我的问题可能是我使用的方程式: int firstDayEachMonth = (daysMonth + firstDayYear)%7;虽然老师把这个方程给我们用了,但是好像不行。

如您所见,第一行的空格一直在左边,它应该与指定的日期对齐,在这种情况下为 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),只能使用扫描仪。

【问题讨论】:

  • 假设这是家庭作业,您是否可以查看标准 Java 库和 API?如果你是,java.util.Calendar 和 java.lang.String.format 可能会感兴趣。特别是,Calendar.roll 将帮助您完成大量工作......
  • 嘿,我们不能使用不同的库,只能使用扫描仪。

标签: java calendar


【解决方案1】:

你能试试这个例子吗? 我可以看到以下输出:

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

【讨论】:

  • 如果你想使用扫描仪,用它来获取月份和年份。让我知道这是否解决了您的问题。
  • 感谢回复,我们还没有学习方法,所以我认为我们不能在我们的代码中实现它。
  • 你能帮我解释一下间距是如何工作的吗?因为我需要打印一年中的所有月份 1 月到 12 月,给定年份和用户的开始日期。在您的程序中,它看起来只显示一个月,这不是我需要帮助的,而是每个月第一行的间距。如果你再看我的帖子,你会看到我想要的图片的另一个链接。
  • @Flinze - 你检查了吗?
  • 我刚刚测试了我正在编写的快速脚本,但输出不准确。它说 2019 年 11 月 1 日是星期日,而实际上是星期五
【解决方案2】:

由于这似乎是一个家庭作业,我不会费心给你正确的算法。这会破坏您(或其他有相同问题的人)练习您的编程和分析技能的目的。

在这一行 for (int space = 1; space &lt;= 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 个空格,你总是给你错误的偏移量,并且会在某些行上造成一些麻烦。

这些是我注意到的,希望对您有所帮助。和平!

【讨论】:

    【解决方案3】:

    java.time

    我建议您使用modern Date-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: Date Time 了解有关现代日期时间 API 的更多信息。


    * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个Android项目工作并且您的Android API级别仍然不符合Java-8,请检查Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

    【讨论】:

      【解决方案4】:
      public class Exercice5_29DisplayCalenderDay {
      
      /**
       * @param args the command line arguments
       */
      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.println("Enter the weekday that the year starts: ");
          int day = input.nextInt();
          int dayCounter = day;
           int nbrOfDays = 0;
           String  monthx = ""; 
          for (int month= 1; month <=12; month++)
          {
      
                              // Switch to chose the month 
                    switch (month)
                   {
                        case 1: monthx = "January";
                                   nbrOfDays = 31;
                                   break;
                        case 2: monthx = "February";
                                           if ( year % 4 == 0 && year % 100 !=0 || year % 400 == 0)
                            {
                                   nbrOfDays = 29;
                                   break;
                            }
                                           else
                               {  nbrOfDays = 28;
                                   break;
                               }
                       case 3: monthx = "March";
                                   nbrOfDays = 31;
                                   break; 
                        case 4: monthx = "April";
                                   nbrOfDays = 30;
                                   break; 
                               case 5: monthx = "May";
                                   nbrOfDays = 31;
                                   break;
      
                               case 6: monthx = "June";
                                   nbrOfDays = 30;
                                   break;
                                case 7: monthx = "July";
                                   nbrOfDays = 31;
                                   break;
                                case 8: monthx = "August";
                                   nbrOfDays = 31;
                                   break;
                          case 9: monthx = "September";
                                   nbrOfDays = 30;
                                   break; 
                          case 10: monthx = "October";
                                   nbrOfDays = 31;
                                   break; 
                          case 11: monthx = "November";
                                   nbrOfDays = 30;
                                   break; 
                               case 12: monthx = "December";
                                   nbrOfDays = 31;
                                   break;                  
                   }
      
                       System.out.printf("%15s %d  \n", monthx , year);
                       System.out.println("----------------------------");
                       System.out.printf("%s %s %s %s %s %s %s\n ", "Sun","Mon","Tue", "Wed", "Thu","Fri","Sat");
      
                       for (int space =1; space<=day; space++) 
                       {
                           System.out.printf("%4s", "    ");
                       }
                       for (int i = 1; i <=nbrOfDays; i++)
                       {
                          dayCounter++;
                          if ( dayCounter% 7==0)
                           System.out.printf("%- 4d\n", i);
                          else
                          System.out.printf("%-4d", i);
      
                       }
                       day = (day + nbrOfDays)%7;
      
                               System.out.println();
      
          }    
      
      }
      }
      

      【讨论】:

        【解决方案5】:

        导入 java.util.Scanner;

        公共类 DisplayCalendar {

        public static void main(String[] args) {
            String Months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
            int numday[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        
            Scanner in = new Scanner(System.in);
            System.out.println("enter the year");
            int year = in.nextInt();
            if ((((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))) {
                numday[1] = 29;
            }
            System.out.println("enter the day start the year ");
            int day = in.nextInt();
            for (int i = 1; i <= 12; i++) {
                System.out.println("\t" + Months[i - 1]+" "+ year);
                System.out.println("ـــــــــــــــــــــــــ");
                System.out.printf("%-4s%-4s%-4s%-4s%-4s%-4s%-4s\n","Sun","Mon","Tue","Wed","Thu","Fri","Sat");
                day = manh(day, numday[i - 1]);
            }
        
        }
        
        public static int manh(int day, int numday) {
            int a[][] = new int[6][7];
            int counter = 1;
            int j = 0;
            for (int i = 0; i < 6; i++) {
                for (j = day; j < 7; j++) {
                    a[i][j] = counter;
                    day++;
                    counter++;
                    if (counter == numday + 1) {
                        break;
                    }
                }
                day = 0;
                if (counter == numday + 1) {
                    break;
                }
        
            }
            for (int i = 0; i < 6; i++) {
                for (int f = 0; f < 7; f++) {
                    System.out.printf("%-4s", a[i][f] == 0 ? "" : a[i][f]);
                }
                System.out.println();
        
            }
            int dayret = j + 1;
            return dayret >= 7 ? 0 : dayret;
        }
        

        }

        【讨论】:

        • 发布代码时,记住两件事很重要。 1)为了避免部分代码在代码块中没有格式化的问题,你可以用三个反引号开始一个代码块:```并用另外3个反引号结束它,2)你应该解释你是如何得到答案的,不仅仅是“这里的代码应该可以工作”
        【解决方案6】:

        这是全年的日历:

        
        public class Main { 
        
            /***************************************************************************
             *  Given the month, day, and year, return which day
             *  of the week it falls on according to the Gregorian calendar.
             *  For month, use 1 for January, 2 for February, and so forth.
             *  Returns 0 for Sunday, 1 for Monday, and so forth.
             ***************************************************************************/
             public static int day(int month, int day, int year) {
                 int y = year - (14 - month) / 12;
                 int x = y + y/4 - y/100 + y/400;
                 int m = month + 12 * ((14 - month) / 12) - 2;
                 int d = (day + x + (31*m)/12) % 7;
                 return d;
             }
         
             // return true if the given year is a leap year
             public static boolean isLeapYear(int year) {
                 if  ((year % 4 == 0) && (year % 100 != 0)) return true;
                 if  (year % 400 == 0) return true;
                 return false;
             }
         
             public static void main(String[] args) {
                 int[] a = {1,2,3,4,5,6,7,8,9,10,11,12};   // month (Jan = 1, Dec = 12)
                 int year = 2022; // year
                 
                 // months[i] = name of month i
                 String[] months = {
                     "",                               // leave empty so that 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 month : a){
         
                 // check for leap year
                 if (month == 2 && isLeapYear(year)) days[month] = 29;
         
         
                 // print calendar header
                 System.out.println("   " + months[month] + " " + year);
                 System.out.println(" S  M Tu  W Th  F  S");
         
                 // starting day
                 int d = day(month, 1, year);
         
                 // print the calendar
                 for (int i = 0; i < d; i++)
                     System.out.print("   ");
                 for (int i = 1; i <= days[month]; i++) {
                     System.out.printf("%2d ", i);
                     if (((i + d) % 7 == 0) || (i == days[month])) System.out.println();
                 }
                 System.out.println("");
               }
             }
         }
        
        
        

        参考:https://introcs.cs.princeton.edu/java/21function/Calendar.java.html

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 2018-03-01
        • 2012-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        相关资源
        最近更新 更多