面向对象的第二次pta作业第四题:求前N天
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int year = input.nextInt(); int month = input.nextInt(); int day = input.nextInt(); int n = input.nextInt(); if(!checkInputValidity(year, month, day, n)) { System.out.println("Wrong Format"); System.exit(0); } nextDate(year, month, day, n); /*nextDate() System.out.println("Next date is:"+year+"-"+month+"-"+day); 也可以*/ } public static boolean isLeapYear(int year) {//判断year是否为闰年,返回boolean类型; boolean y1 = year%4 == 0; boolean y2 = year%100 != 0; boolean y3 = year%400 == 0; if(y1&&y2||y3) return true; else return false; } public static boolean checkInputValidity(int year,int month,int day,int n) {//判断输入日期及n的值是否合法,返回布尔值 if(year>2020||year<1820||month>12||month<1||day<1||day>31) { return false; } if(n>10||n<(-10)) return false; switch (month) { case 4:case 6:case 9:case 11: if(day>30) return false; break; case 2: if(isLeapYear(year)&&day>29) return false; if(day>28) return false; break; } return true; } public static void nextDate(int year,int month,int day,int n) { //求输入日期的前n天 int arr[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; if(isLeapYear(year)) arr[2]++; if((day-n)<=arr[month]&&(day-n)>=1)// day = day-n; else if((day-n)>arr[month]&&month<12) {// day = day-n-arr[month]; month++; } else if((day-n)<1&&month>1) { month--; day = day-n+arr[month]; } else if((day-n)>arr[month]&&month==12) { day = day-n-arr[month]; month = 1; year++; } else if((day-n)<1&&month==1) { month=12; day = day-n+arr[month]; year--; } System.out.println(n+" days ago is:"+year+"-"+month+"-"+day); } }
分不清c和Java的小熊同学被日期代码的3.0版本吓懵了