fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int year; // year
  13. int startDayOfMonth;
  14. int spaces;
  15. int month;
  16.  
  17. //Creates a new Scanner
  18. Scanner scan = new Scanner(System.in);
  19.  
  20. //Prompts user to enter year
  21. System.out.println("Enter a year: ");
  22. year = scan.nextInt();
  23.  
  24. //Prompts user to enter month
  25. System.out.println("Enter the number of the month: ");
  26. month = scan.nextInt();
  27.  
  28.  
  29. //Calculates the 1st day of that month
  30. Calendar cal = Calendar.getInstance();
  31. cal.set(year, month-1, 1);
  32. int day = cal.get(Calendar.DAY_OF_WEEK)-1;
  33.  
  34. // months[i] = name of month i
  35. String[] months = {
  36. " ",
  37. "January", "February", "March",
  38. "April", "May", "June",
  39. "July", "August", "September",
  40. "October", "November", "December"
  41. };
  42.  
  43. // days[i] = number of days in month i
  44. int[] days = {
  45. 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  46. };
  47.  
  48.  
  49. // check for leap year
  50. if ((((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) && month == 2)
  51. days[month] = 29;
  52.  
  53.  
  54. // print calendar header
  55. // Display the month and year
  56. System.out.println(" "+ months[month] + " " + year);
  57.  
  58. // Display the lines
  59. System.out.println("___________________________________________");
  60. System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
  61.  
  62. // spaces required
  63. spaces = day;
  64.  
  65. // print the calendar
  66. for (int i = 0; i < spaces; i++)
  67. System.out.print(" ");
  68. for (int i = 1; i <= days[month]; i++) {
  69. System.out.printf(" %4d ", i);
  70. if (((i + spaces) % 7 == 0) || (i == days[month])) System.out.println();
  71. }
  72.  
  73. System.out.println();
  74. }
  75. }
Success #stdin #stdout 0.13s 30236KB
stdin
2018
2
stdout
Enter a year: 
Enter the number of the month: 
              February 2018
___________________________________________
  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