之前做过的一道面试题,要求:输入某年某月某日,判断这一天是这一年的第几天。
代码:
import java.util.Scanner;
public class Test {
//输入某年某月某日,判断这一天是这一年的第几天?
public static int getDay(String strDay){
String[] time = strDay.split("-");
int year = Integer.parseInt(time[0]);
int month = Integer.parseInt(time[1]);
int day = Integer.parseInt(time[2]);
int count = day;//总数
int twoMonth = 28;//二月份的天数
//判断是否为闰年,是则二月份的天数加一
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
twoMonth = 29;
}
//月份的天数,写进数组中
int[] monthCount = {31,twoMonth,31,30,31,30,31,31,30,31,30,31};
for (int i = 0; i < month-1; i++) {
count += monthCount[i];
}
return count;
}
public static void main(String[] args) {
// 输入某年某月某日,判断这一天是这一年的第几天?
Scanner day = new Scanner(System.in);
System.out.println("请输入一个日期,格式 yyyy-MM-dd : ");
String strDay = day.next();
System.out.println("这一天是这一年的第" + getDay(strDay) + "天");
}
}