输入年月 打印万年历

package com.test;
import java.util.Calendar;
import java.util.Scanner;

public class WanNianLi {

public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 用户输入年月,打印该月份万年历 
* 1 创建扫描器 2 获取输入 3 判断月份天数 4设置数据5打印
*/
// 扫描器
Scanner scanner = new Scanner(System.in);
// 获取输入
System.out.println("请输入年份:");
int year = scanner.nextInt();
System.out.println("请输入月份");
int month = scanner.nextInt();
int days = 0;
// 计算一下每个月的天数
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if (year % 4 == 0) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("请输入正确的月份(1-12)");
break;
}

// 创建一个calendar 设置对象的年月为输入的值
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 计算该月的第一天是周几
int week = calendar.get(Calendar.DAY_OF_WEEK);
int count = 0;// 计数器

System.out.println("周日\t周一\t周二\t周三\t周四\t周五\t周六");

// 打印空格
for (int i = 0; i < week - 1; i++) {
count++;
System.out.print("\t");
}
// 打印天
for (int day = 1; day < days + 1; day++) {
count++;



System.out.print(day + "\t");   

                 //每七天跳转一行

if (count % 7 == 0) {
System.out.println();
}
}
}
}

 

你可能感兴趣的:(java)