用java编写一个程序GregorianCalendar实现日历系统,默认输出当月的日历数据
时间: 2024-05-24 15:13:28 浏览: 180
好的,让我看看:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
public class CalendarSystem {
public static void main(String[] args) {
//获取当前的GregorianCalendar对象
GregorianCalendar cal = new GregorianCalendar();
//设置当前日期的天数为1
cal.set(Calendar.DAY_OF_MONTH, 1);
//获取当前月份、年份
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
//获取当月的天数
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//获取当前星期几
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
//创建一个格式化字符串,用于输出日历
String format = "%4d年%2d月%n";
System.out.printf(format, year, month);
System.out.println("日 一 二 三 四 五 六");
//填充当月前面的空白
for (int i = 1; i < dayOfWeek; i++) {
System.out.print(" ");
}
//输出当月的天数
for (int i = 1; i <= daysInMonth; i++) {
//如果当前是周六,换行
if (dayOfWeek == Calendar.SATURDAY) {
System.out.printf("%2d%n", i);
} else {
System.out.printf("%2d ", i);
}
//将dayOfWeek加1
dayOfWeek++;
//如果dayOfWeek超过了周六,将其设置为周日
if (dayOfWeek > Calendar.SATURDAY) {
dayOfWeek = Calendar.SUNDAY;
}
}
}
}
希望这个程序对你有所帮助!
阅读全文