1.问题重述
题目:输入某年某月某日,判断这一天是这一年的第几天?
2.解析
2.1天数如何计算
创建一个数组存储非闰年每个月的天数,输入月份时,遍历之前的天数并相加;如为闰年且月份大于2时,总天数应加一。
2.2错误判断
- 输入的年份大小是否合理
- 输入的月份是否合理
- 输入的天数是否合理(与数组中的数据做比较,小于数组中对应月份的天数即合理)
3.解决问题
代码如下(如有问题,欢迎私聊我讨论):
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
int[] Mouth = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
int sum = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("请依次输入年、月、日:");
int year = scanner.nextInt();
int mouth = scanner.nextInt();
int day = scanner.nextInt();
if(year < 0) {//年份判断是否正确
System.out.println("error");
}else {
if(mouth < 1 || mouth > 12) {//判断月份是否有误
System.out.println("error");
}else if(year%400 == 0 || (year%4 == 0 && year%100 !=0)) {//当是闰年时
if(mouth == 1 || mouth == 2) {//如果为1月和2月时
if(mouth == 2) {//2月时
if(day >= 30) {//判断天是否出错
System.out.println("error");
}else {//2月的天数算法
sum = Mouth[0] + day;
}
}else if(day > Mouth[mouth-1]) {//天数正误判断
System.out.println("error");
}else {//元月天数判断
sum = day;
}
}else {//如果为3月~12月时
if(day > Mouth[mouth-1]) {//判断天数是否出错
System.out.println("error");
}else {//sum的天数判断
for(int i = 0;i < mouth-1;i++) {
sum += Mouth[i];
}
sum += day;
sum++;
}
}
}else {//非闰年计算
if(day > Mouth[mouth-1]) {//天数正误判断
System.out.println("error");
}else {//正确的日期的天数计算
for(int i = 0;i < mouth-1;i++) {
sum += Mouth[i];
}
sum += day;
}
}
}
if(sum == 0) {
}else {
System.out.println(year + "年"+ mouth + "月" + day + "日" + "是这一年的第" + sum + "天");
}
}
}