java编写日历
java编写日历
代码
`import java.util.Scanner;
public class Calendar1{
public static int monthday,year,month,day;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(“请输入当前日期,年月日用空格隔开:”);
String temp = sc.nextLine();
String[] ss = temp.split(" “); //split() 方法根据匹配给定的正则表达式来拆分字符串。
year = Integer.parseInt(ss[0]); //parseInt() 方法用于将字符串参数作为有符号的十进制整数进行解析。
month = Integer.parseInt(ss[1]);
day = Integer.parseInt(ss[2]);
boolean flag2 = isRun(year);
if(flag2){
System.out.println(”\t\t"+“闰年”);
}else{
System.out.println("\t\t"+“平年”);
}
getdays(year,month);
Calendar(year,month,day);
}
public static boolean isRun(int year){
if((year%4==0&&year%100!=0)||year%400==0) {
return true;
}else {
return false;
}
}
public static int getdays(int year,int month){
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) {
monthday=31;
}else if(month==4||month==6||month==9||month==11){
monthday=30;
}else if(month==2){
boolean flag1 = isRun(year);
if(flag1){
monthday = 29;
}else{
monthday = 28;
}
}
return monthday;
}
public static int Calendar(int y,int m,int d){
int startDay,w,w1;
if(m == 1 || m == 2)
{
m += 12;
y--;
}
/*基姆拉尔森计算公式
* Week=(Day + 2*Month + 3*(Month+1)/5 + Year
* + Year/4 - Year/100 + Year/400) % 7 */
w = (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)+1;
while(w>7) {
w=w-7;
}
//判断每个月第一天是周几,来确定日历日期开始的位置
w1 = (2*m+3*(m+1)/5+y+y/4-y/100+y/400)+2;
while(w1>7) {
w1=w1-7;
}
if(w1==7) {
startDay=0;
}else {
startDay=w1;
}
//显示内容
System.out.println("\t"+year+"年"+month+"月"+day+"日"+"星期"+w);
System.out.println("-----------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
int i;
for (i = 0; i < startDay; i++)
System.out.print(" "); //开始日期不为周日,则在前面补空格
for (i = 1; i <= monthday; i++) {
if (i < 10)
System.out.print(" " + i);
else
System.out.print(" " + i);//为了界面和谐,十位数比个位数少一个空格
if ((i + startDay) % 7 == 0) //判断何时该换行输出
System.out.println();
}
return w;
}
}`