如何在java中显示日历

时间:2016-02-28 07:17:03

标签: java calendar

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

以下是我目前的一个月内显示的内容:

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

    }
}   

5 个答案:

答案 0 :(得分: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 = startSayOfMonth; // 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 :(得分:1)

由于这似乎是一项家庭作业,因此我不会费心为您提供正确的算法。那会破坏您或其他有相同问题的人的目的,即练习您的编程和分析技能。

在这一行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个空格,总是给您错误的偏移量,并且会在某些行上引起麻烦。

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

答案 2 :(得分:1)

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 了解有关现代 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

答案 3 :(得分:0)

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

    }    

}
}

答案 4 :(得分:0)

导入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;
}

}