面向对象的第二次pta作业第二题:判断闰年及星期几
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(); if(year>2020||year<1820||month>12||month<1||day<1||day>31) { System.out.println("Wrong Format"); System.exit(0); } switch (month) { case 4:case 6:case 9:case 11: if (day>30) { System.out.println("Wrong Format"); System.exit(0); } break; case 2: if (isLeapYear(year)&&day>29) { System.out.println("Wrong Format"); System.exit(0); } if (day>28) { System.out.println("Wrong Format"); System.exit(0); } break; } boolean l = isLeapYear(year); int days = numOfDays(year, month, day); String b = " not "; if(l) b = " "; System.out.println(year+" is"+b+"a leap year."); System.out.println(year+"-"+month+"-"+day+" is "+getWhatDay(days)+"."); } 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 int numOfDays(int year,int month ,int day) {//求出year-month-day到0001-1-1的距离天数,返回整型数; int arr[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; int i,j,d = 0; for(i=1;i<year;i++) { d=d+365; if(isLeapYear(i)) d++; } for(j=1;j<month;j++) d=d+arr[j]; d=d+day; if(isLeapYear(year)&&month>2) d++; return d; } public static String getWhatDay(int days) {//根据天数返回星期几,其中参数days为天数,整型数,返回星期几的英文单词。 String whatDay = null; int s = days%7; switch (s) { case 1: whatDay = "Monday";break; case 2: whatDay = "Tuesday";break; case 3: whatDay = "Wednesday";break; case 4: whatDay = "Thursday";break; case 5: whatDay = "Friday";break; case 6: whatDay = "Saturday";break; case 0: whatDay = "Sunday";break; } return whatDay; } }
哎呀学c的时候我就不喜欢日期题啦
达成新成就——boolean的用法~(好像很方便耶)