In: Computer Science
Write a java program MyCalendar that outputs a monthly calendar
for a given month and year.
the output should be looks like this one at the bottom:( I don't
know why it doesn't show right but the first day of the month is
not Sunday it starts from Wednesday)
F. Last’s My Calendar
Enter month year? 10 2019
10/2019
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 31
I think your sample output in question have problem that first day of month should be Tuesday not Wednesday. Below is correct code if you want any modification or have any problems let me know.
MyCalendar.java file:
package calendar;
import java.util.Calendar;
import java.util.Scanner;
public class MyCalendar {
// main method to run program
public static void main(String args[]) {
// create a Scanner object to read
input from user
Scanner s = new
Scanner(System.in);
// prompt user for input date and
year
System.out.print("Enter month year?
");
String input = s.nextLine(); //
read input from user
s.close(); // close the scanner as
done reading input
String[] data = input.split(" ");
// Separate month from year
int month =
Integer.parseInt(data[0]);
int year =
Integer.parseInt(data[1]);
// create a calendar object
Calendar c =
Calendar.getInstance();
// set given date to calendar
c.set(year,month-1,1); // remove 1
from month as months are 0 indexed
// get the 1st day of the
month
int day =
c.get(Calendar.DAY_OF_WEEK);
// get maximum days of month
int max_days =
c.getActualMaximum(Calendar.DAY_OF_MONTH);
// print calendar
System.out.println(month + "/" +
year); // print month
// Format string for output days
name
String days_name =
String.format("%s %s %s %s %s %s %s", "
Sun","Mon","Tue","Wed","Thu","Fri","Sat");
// print name of days
System.out.println(days_name);
System.out.println("----------------------------");
//print days
for(int
i=1;i<max_days+day+1;i++) {
int date = i -
day;
// get formated
output for days
String days =
"";
if(date > 0)
{
days = String.format("%4s", date);
}
else {
days = String.format("%4s", " ");
}
System.out.print(days);
//print new line
at end of week
if(i%7==0)
{
System.out.println();
}
}
}
}