import java.util.Scanner; public class Test20 { public static void main(String[] args) { System.out.println("请输入日期,年月日按空格隔开"); Scanner sc = new Scanner(System.in); int year = sc.nextInt(); int month = sc.nextInt(); int day = sc.nextInt(); int towMonth = 28; if ((year % 400 == 0) | (year % 4 == 0 && year % 100 != 0)) { towMonth = 29;//闰年多一天 } int totalDay = 0; int[] months = {31, towMonth, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (month>12||day>months[month-1]){ //判断月份不能大于12,日不能大于当前月份最大的天数,否则不合法 System.out.println("日期不合法,请重新输入!"); }else { if (month == 1) { //如果月份等于1,那么直接输出是第day天 System.out.println("天数为" + year + "年的第" + day + "天"); } else { //非1月情况下,调用数组从1月加到月份-1月,最后在将总和与day相加就是总天数 for (int i = 0; i < month - 1; i++) { totalDay += months[i]; } totalDay += day; System.out.println("天数为" + year + "年的第" + totalDay + "天"); } } } }
正确输入
错误输入