Comment afficher le calendrier en java


Je fais actuellement un jeu de problèmes où je dois créer un calendrier affichant tous les mois d'une année, y compris les jours du mois qu'il contient. Cependant, j'ai des problèmes avec l'espacement de la première ligne de chaque mois. En classe, nous avons seulement appris les instructions switch, if, else, while, do-while, for boucles

Voici ce qui est actuellement affiché pour un de mes mois:

L'Image de sortie Dans l'image est ne montre pas mes entrées, mais ce que j'ai écrit était 2016 pour l'année et 5 pour le jour de la semaine où l'année commence.

Image de sortie de ce que ce qui est désiré Encore une fois, une image de ce qui est désiré. Je pense que mon problème est peut-être l'équation que j'ai utilisée qui est: int firstDayEachMonth = (daysMonth + firstDayYear)%7; bien que l'enseignant nous ait donné cette équation à utiliser, mais il semble que cela ne fonctionne pas.

Comme vous pouvez voir les espaces sur la première ligne est tout le chemin vers la gauche, il devrait être aligné avec les dates désignées, dans ce cas pour janvier, le 1er janvier devrait s'aligner le vendredi et le 2 janvier devrait s'aligner sur le samedi, mais c'est actuellement le dimanche et le lundi.

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

}

}

Author: Flinze, 2016-02-28

3 answers

Puisque cela semble être un devoir, je ne vais pas prendre la peine de vous donner le bon algorithme. Cela irait à l'encontre du but de vous - ou d'autres personnes ayant le même problème - pratiquer vos compétences en programmation et en analyse.

Dans cette ligne for (int space = 1; space <= firstDayEachMonth; space++) vous pouvez totalement ignorer le résultat firstDayEachMonth et utiliser votre compteur firstDayYear. Ce compteur a le jour de semaine de départ de l'année et il est incrémenté chaque jour qui passe. En outre, il est nécessaire de définir si votre semaine commence à 0 ou 1.

Dans cette partie, vous sont déjà mettre un saut de ligne pour la fin de la semaine ici:

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

Je réinitialiserais firstDayYear lorsque vous atteindrez cette condition car puisque vous l'utilisez comme paramètre pour définir vos espaces, vous n'aurez jamais ce nombre supérieur à 7. De cette façon, vous avez chaque semaine ligne disposées correctement sur le calendrier et le seul problème serait de les présenter dans le bon format à l'écran.

Lorsque vous imprimez l'en-tête jours de la semaine comme ceci System.out.println("Sun Mon Tue Wed Thu Fri Sat"); gardez à l'esprit que vous avez les noms avec longueur 3 plus 5 espaces blancs. Donc, cette ligne System.out.printf("%3d ", daysDisplay); doit avoir un chiffre avec une largeur de 3 espaces, ce qui explique l'utilisation de %3d, majoré de 5 espaces. Dans ce cas, vous avez 6 espaces que vous vous donnez toujours le mauvais décalage et provoquera un enfer sur certaines lignes.

Ce sont les choses que j'ai remarquées et j'espère que cela aide. La paix!

 1
Author: Luan Moraes, 2018-09-30 15:44:50

Pouvez-vous essayer cet exemple? Je peux voir la sortie suivante:

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

}

 0
Author: Learner, 2016-02-29 02:35:20
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();

    }    

}
}
 0
Author: Ben Kamit, 2017-07-21 17:35:00