Java 输入一个日期,判断是星期几

package com.zwg.calweek;
import java.time.MonthDay;
import java.util.Scanner;
public class CalMain {
public static void main(String[] arge){
Scanner sc=new Scanner(System.in);
int year,month,day;
while(true){
System.out.println("我可以计算你输入的日期是星期几,请依次输入年月日");
System.out.println("请输入年份:");
year=sc.nextInt();
while(year<1900){
System.out.println("我还无法计算1900之前的日期");
System.out.println("请重新输入年:");
year=sc.nextInt();
}
System.out.println(CheckDay.isLeap(year));
System.out.println("请输入月份:");
month=sc.nextInt();
while(month>12||month<1){
System.out.println("月份输入错误,请重新输入:");
month=sc.nextInt();
}
System.out.println("请输入日:");
day=sc.nextInt();
while(!CheckDay.checkDay(year,month,day)){
day=sc.nextInt();
}
System.out.println("日期输入完毕,正在计算...");
FinalCal.finalCal(year, month, day);
}

}}

/*---------------------------------------------------------------------------*/

package com.zwg.calweek;


public class CheckDay {
public static boolean isLeap(int year){
boolean mark=false;
if((year%4==0&&year%100!=0)||year%400==0)
mark=true;
return mark;
}
public static boolean checkDay(int year, int month,int day){
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(day<1||day>31)
return false;
break;
case 4:
case 6:
case 9:
case 11:
if(day<1||day>30)
return false;
break;
case 2:
if(isLeap(year)){
if(day<1||day>29)
{
System.out.println(year+"年2月有29天");
return false;
}
}
else {
if(day<1||day>28)
{
System.out.println(year+"年2月有28天");
return false;
}
}break;
default:
System.out.println("Error! checkDay函数出错");
}
return true;
}
}/*------------------------------------------------------------------------------------------*/

package com.zwg.calweek;


public class FinalCal {
public static void finalCal(int year,int month,int day){
/**1.计算该年与1900年间有几个闰年,有几个,就额外+几天;
 * 1904是第一个闰年; 
 */
int y=year-1904,count=0;
if(y>=0)
count=y/4+1;
int total;
total=(year-1900)*365+calMonth(month-1)+day+count;
int week=total%7;
System.out.print(year+"年"+month+"月"+day+"日是星期");
switch(week){
case 1:
System.out.println("一");break;
case 2:
System.out.println("二");break;
case 3:
System.out.println("三");break;
case 4:
System.out.println("四");break;
case 5:
System.out.println("五");break;
case 6:
System.out.println("六");break;
case 7:
System.out.println("日");break;
default:
System.out.println("error week");
}
System.out.println();
}
public static int calMonth(int month){
switch(month){
case 0:return 0;
case 1:return 31;
case 2:return 31+28;
case 3:return 31+28+31;
case 4:return 31+28+31+30;
case 5:return 31+28+31+30+31;
case 6:return 31+28+31+30+31+30;
case 7:return 31+28+31+30+31+30+31;
case 8:return 31+28+31+30+31+30+31+31;
case 9:return 31+28+31+30+31+30+31+31+30;
case 10:return 31+28+31+30+31+30+31+31+30+31;
case 11:return 31+28+31+30+31+30+31+31+30+31+30;
case 12:return 31+28+31+30+31+30+31+31+30+31+30+31;
default:
System.out.println("Error! calMonth");
return 0;
}
}


}


你可能感兴趣的:(算法,Java)