问题
在控制台输入一个年份和月份,在控制台输出这个月的日历。
基本思路
先计算某年某月的第一天距离1900.1.1的天数。然后用天数%7,就可以得到这一天是星期几。然后对这个月进行遍历存储在二维数组中。
日期类
package day06;
public class Date {
private int year;
private int month;
public Date(int year,int month) {
this.year = year;
this.month = month;
}
public Date() {
}
public int setYear(int yesr ) {
return this.year = yesr;
}
public int setMonth(int month) {
return this.month = month;
}
// 计算xx年xx月距离1900.1.1有多少天
public int getDays() {
int days = 0;
for(int i = 1900; i<year;i++) {
if(i%4==0&&i%100!=0||i%400==0) {
days = days +366;
}
else {
days = days +365;
}
}
for(int i = 1;i<month;i++) {
days = days +this.getMonthDays(i);
}
return days+1;
}
// 计算月份的天数
public int getMonthDays(int month) {
int monthDays = 0;
if(month==2) {
if(year%4==0&&year%100!=0||year%400==0) {
monthDays = monthDays+29;
}
else {
monthDays = monthDays+28;
}
}else if(month==4||month==6||month==9||month==11) {
monthDays = monthDays+30;
}else {
monthDays = monthDays+31;
}
return monthDays;
}
// 将某月的日历放在二维数组中
public String[][] getRiLi() {
String[][] riLi = new String[7][7];
Integer m = 1;
riLi[0][0] = "\t日"; riLi[0][1]= "\t一"; riLi[0][2] = "\t二";
riLi[0][3] = "\t三"; riLi[0][4] = "\t四"; riLi[0][5] = "\t五";
riLi[0][6] = "\t六";
for(int j= 0;j<this.getDays()%7;j++) {
riLi[1][j] = "\t";
}
for(int j= this.getDays()%7;j<7;j++) {
riLi[1][j] ="\t"+m.toString();
m++;
}
for(int i = 2; i<7;i++) {
for(int j = 0;j<7;j++,m++) {
if(m>this.getMonthDays(month)) {
riLi[i][j] ="\t";
}
else {
riLi[i][j] ="\t"+m.toString();
}
}
}
return riLi;
}
}
用户进行交互的控制台代码
package day06;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Work1 {
// 判断字符串是否为数字
private static boolean isNumeric(String str) {
// TODO Auto-generated method stub
boolean flag = false;
for(int i =0 ; i<str.length();i++) {
char ch = str.charAt(i);
if (ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7'
|| ch == '8' || ch == '9') {
flag = true;
} else {
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args) {
Date d1 = new Date();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("请输入要查询的年份月份或者输入退出结束程序。");
String str = null;
try {
str = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] s = str.split(" ");
if (isNumeric(str)) {
Integer year = Integer.parseInt(s[0]);
Integer month = Integer.parseInt(s[1]);
if ((year > 1900) && (month >= 1 && month <= 12)) {
d1.setYear(year);
d1.setMonth(month);
String[][] rili = d1.getRiLi();
for (String[] k : rili) {
for (String v : k) {
System.out.print(v);
}
System.out.println();
}
} else {
System.out.print("输入错误");
}
} else if (str.equals("退出")) {
System.out.println("程序结束");
break;
} else {
System.out.println("输入错误");
}
}
}
}