业务逻辑类
package test; public class InputDateOutputDayCount { //该变量统计总天数 private int countDay = 0; //年 int year; //月 int month; //日 int day; //该方法获取天数 public int getCountDay(String date){ //截取年月日 String strArr[] = date.split("-"); //转换为整型并赋值给年月日 year = Integer.parseInt(strArr [0]); month =Integer.parseInt(strArr[1]); day = Integer.parseInt(strArr[2]); for (int i = 0; i < month; i++) { //获取天数并返回 switch (i){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: countDay += 31; break; case 4: case 6: case 9: case 11: countDay += 30; break; case 2: countDay += 28; break; } } //判断是否为闰年 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ){ //是闰年并且月份大于2,天数就就加一天,否则不加 if (month>2){ countDay = countDay + day + 1; return countDay; } countDay += day; return countDay; }else { countDay = countDay + day; return countDay; } } }
测试类
package test; import java.util.Scanner; public class InputDateOutputDayCountTest { //测试方法 public static void main(String[] args){ //录入函数 Scanner scanner = new Scanner(System.in); //输入年份 System.out.println("请输入年份:"); String year = scanner.next(); //输入月份 System.out.println("请输入月份:"); String mounth = scanner.next(); //输入日 System.out.println("请输入日:"); String day = scanner.next(); String date = year + "-" + mounth + "-" + day; //调用方法 InputDateOutputDayCount idody = new InputDateOutputDayCount(); //输出这一天是这一年中的第几天 System.out.println(date + "是" + year + "年中的第" + idody.getCountDay(date) + "天。"); } }