题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以 3 月 5 日为例,应该先把前两个月的加起来,然后再加上 5 天即本年的第几天,特殊情况,闰年且输入月份大于 3 时需考虑多加一天。
import java.util.Scanner;
public class WangDao {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter year: ");
int year = scan.nextInt();
System.out.print("Enter month: ");
int month = scan.nextInt();
System.out.print("Enter day: ");
int day = scan.nextInt();
int[][] arr = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
int x = 0, whichDay = 0;
if (isLeapYear(year)) {
x = 1;
} else {
x = 0;
}
for (int i = 1; i < month; i++) {
whichDay += arr[x][i];
}
whichDay += day;
System.out.println("This day is the " + whichDay + "th day of the year.");
}
public static boolean isLeapYear(int n) {
boolean flag = false;
if ((n % 400 == 0) || (n % 100 != 0 && n % 4 == 0)) {
flag = true;
}
return flag;
}
}