判断一天是一年中的第几天
基本思想:
想要判断一天是一年当中的第几天,就需要把当月之前的月份天数都加起来,然后加上当月的号数(比如说4月7日,就是4月份之前的月份天数加上7)。
以3月1日为例,应该先把前两个月的加起来,然后再加上几日即本年的第几天, 特殊情况:闰年且输入月份大于3时需考虑多加一天;
方法一:
package homework08.homework0823;
import java.util.Scanner;
public class Demo {
//判断一天是这一年的第几天
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年: ");
int year= scanner.nextInt();
System.out.print("请输入月: ");
int month= scanner.nextInt();
System.out.print("请输入日: ");
int day= scanner.nextInt();
int result = 0;
if (month > 1) {
result += 31;
}
if (month > 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
result += 29;
} else {
result += 28;
}
}
if (month > 3) {
result += 31;
}
if (month > 4) {
result += 30;
}
if (month > 5) {
result += 31;
}
if (month > 6) {
result += 30;
}
if (month > 7) {
result += 31;
}
if (month > 8) {
result += 31;
}
if (month > 9) {
result += 30;
}
if (month > 10) {
result += 31;
}
if (month > 11) {
result += 30;
}
System.out.println(result + day);
}
}
效果图如下:
方法二:用switch写出一天是一年当中的第几天
package homework08.homework0823;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年: ");
int a = scanner.nextInt();
System.out.print("请输入月: ");
int b = scanner.nextInt();
System.out.print("请输入日: ");
int c = scanner.nextInt();//从键盘获取年月日;
int result = 0;//用来接受月份天数
int flag = 0;//判断:是平年就加0,闰年就加1;
if ((a % 4 == 0 && a % 100 != 0) || (a % 400 == 0)) {
flag = 1;
}
switch (b) {
case 12:
result += 30;
case 11:
result += 31;
case 10:
result += 30;
case 9:
result += 31;
case 8:
result += 31;
case 7:
result += 30;
case 6:
result += 31;
case 5:
result += 30;
case 4:
result += 31;
case 3:
result = result + 28 + flag;
case 2:
result += 31;
case 1:
System.out.println(result + c);
break;
default:
System.out.println("输入错误,请重新输入!");
}
}
}
效果图如下: