(显示日历)重写程序清单6-12中的PrintCalendar类,使用Calendar和GregorianCalendar类显示一个给定月份的日历。程序从命令行得到月份和年份的输入,例如:java Exercise13_04 5 2016 这个会显示如图13-9中的日历。 也可以不输入年份来运行程序。这种情况下, 年份就是当前年份。如果不指定月份和年份来运行 程序,那么月份就是当前月份。 c:\exercise>java Exercise13_04 5 2016 May,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 30 31 c:\exercise> 图 13-9 程序显示2016年五月的日历
时间: 2023-12-31 22:07:01 浏览: 140
很抱歉,我作为一个语言模型,没有办法展示图像。但是我可以给你提供一个示例代码,你可以在本地运行它来查看日历。
```java
import java.util.Calendar;
import java.util.GregorianCalendar;
public class PrintCalendar {
public static void main(String[] args) {
int month, year;
if (args.length == 2) {
month = Integer.parseInt(args[0]);
year = Integer.parseInt(args[1]);
} else if (args.length == 1) {
month = Integer.parseInt(args[0]);
year = Calendar.getInstance().get(Calendar.YEAR);
} else {
Calendar now = Calendar.getInstance();
month = now.get(Calendar.MONTH) + 1; // Calendar.MONTH starts from 0
year = now.get(Calendar.YEAR);
}
// Create a Gregorian calendar for the given month and year
Calendar cal = new GregorianCalendar(year, month-1, 1);
// Print the calendar header
String[] monthNames = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
System.out.println(monthNames[month-1] + ", " + year);
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
// Determine the starting day of the week
int startDay = cal.get(Calendar.DAY_OF_WEEK) - 1; // Calendar.DAY_OF_WEEK starts from 1
// Move the calendar back to the beginning of the week
cal.add(Calendar.DAY_OF_MONTH, -startDay);
// Print the calendar
while (cal.get(Calendar.MONTH) == month-1) {
for (int i = 0; i < 7; i++) {
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
cal.add(Calendar.DAY_OF_MONTH, 1);
if (cal.get(Calendar.MONTH) != month-1) {
break;
}
}
System.out.println();
}
}
}
```
你可以在命令行中运行该程序并传递月份和年份参数,如下所示:
```
java PrintCalendar 5 2016
```
或者只传递月份参数,以显示当前年份的月历:
```
java PrintCalendar 5
```
或者不传递任何参数,以显示当前月份和年份的月历:
```
java PrintCalendar
```
阅读全文