用java计算日期
目的
计算固定日期在一年中是第几天
方法
1.扫描键盘输入的年月日
2.存储变量
3.定义变量值
4.输出
代码
import java.io.PrintStream;
import java.util.Scanner;
import static java.lang.System.*;
public class demo07 {
public static void main(String[] args) {
Scanner sc = new Scanner(in);
out.print(“输入年份”);
int year = sc.nextInt();
out.print(“输入月份”);
int month = sc.nextInt();
out.print(“输入日”);
int date = sc.nextInt();
if (month > 13 || month < 1) {
out.println("月份非法");
exit(0);
}
int maxDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
maxDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
maxDays = 30;
break;
case 2:
maxDays = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28;
break;
}
if (date < 1 || date > maxDays) {
out.println("日期非法");
exit(0); }
int sumOfDays = date;
switch (month - 1) {
case 11:
sumOfDays += 30;
case 10:
sumOfDays += 31;
case 9:
sumOfDays += 30;
case 8:
sumOfDays += 31;
case 7:
sumOfDays += 31;
case 6:
sumOfDays += 30;
case 5:
sumOfDays += 31;
case 4:
sumOfDays += 30;
case 3:
sumOfDays += 31;
case 2:
sumOfDays += ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28;
case 1:
sumOfDays += 31;
}
System.out.printf("%d年 %d月 %d日 有%d天", year, month, date, sumOfDays);
}
}