输入日期,输出日期对应的 星期
[Java] 纯文本查看 复制代码 import java.math.BigDecimal;
import java.util.Scanner;
public class Demo03
{
public static void main(String[] args) {
int[] date = new int[3];
Scanner sc = new Scanner(System.in);
try {
for (int i = 0; i < date.length; i++) {
System.out.println("请输入" + (i == 0 ? "年(1-100000)" : i == 1 ? "月(1-12)" : "日(根据实际判断)") + ":");
date[i] = sc.nextInt();
}
MyDate md = MyDate.getInstance(date[0], date[1], date[2]);
System.out.println(md.year + "年" + md.month + "月" + md.day + "日是:" + md.getWeek());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
class MyDate
{
// 实列
private static MyDate md = new MyDate();
// 类变量
public static int year;
public static int month;
public static int day;
// 单列设计模式
private MyDate() {
super();
}
// 获取实列对象
public static MyDate getInstance(int year, int month, int day) {
md.isUseDay(year, month, day);
MyDate.year = year;
MyDate.month = month;
MyDate.day = day;
return md;
}
// 获取星期
public String getWeek() {
switch (getTotalDay() % 7) {
case 1:
return "星期一";
case 2:
return "星期二";
case 3:
return "星期三";
case 4:
return "星期四";
case 5:
return "星期五";
case 6:
return "星期六";
case 7:
return "星期日";
}
throw new RuntimeException("抱歉,出错了 ~~");
}
// 获取总共相差多少天
private int getTotalDay() {
int td = 0;
// year 年过去的天数
for (int i = 1; i <= month; i++) {
if (i != month) {
td += getMonthDay(year, i);
}
else {
td += day;
}
}
// 除 year 年以前过去的天数
for (int i = 1; i < year; i++) {
for (int j = 1; j <= 12; j++) {
td += getMonthDay(i, j);
}
}
return td;
}
// 判断 天数是否有效
private void isUseDay(int year, int month, int day) {
isUseYear(year);
isUseMonth(month);
int d = getMonthDay(year, month);
if (!(new BigDecimal(day).compareTo(new BigDecimal("0")) > 0
&& new BigDecimal(day).compareTo(new BigDecimal(d)) <= 0)) {
throw new RuntimeException("日期输入有误!");
}
}
// 判断是否 有效年
private void isUseYear(int year) {
if (!(new BigDecimal(year).compareTo(new BigDecimal("0")) > 0
&& new BigDecimal(year).compareTo(new BigDecimal("100000")) <= 0)) {
throw new RuntimeException("年份输入有误!");
}
}
// 判断 是否 有效月
private void isUseMonth(int month) {
if (!(new BigDecimal(month).compareTo(new BigDecimal("0")) > 0
&& new BigDecimal(month).compareTo(new BigDecimal("12")) <= 0)) {
throw new RuntimeException("月份输入有误!");
}
}
// 获取当年当月天数
private int getMonthDay(int year, int month) {
switch (month) {
// 大月
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isRunNian(year)) {
return 29;
}
return 28;
}
throw new RuntimeException("抱歉,出错了 ~~");
}
// 判断是否是闰年
private boolean isRunNian(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0 && year % 3200 != 0) || year % 172800 == 0) {
return true;
}
return false;
}
}
|