Java程序猿必做50题之四:输入某年某月某日,判断这一天是这一年的第几天?
程序员文章站
2024-03-12 15:54:38
...
题目:
输入某年某月某日,判断这一天是这一年的第几天?
思路:
第一、这里我们可以使用switch语句来解决问题;
第二、设置变量days统计天数;
第二、分别输入年月日,判断month是那个月,计算第几天(这一天的前面有多少天:总共天数days);
第三、如果是闰年,并且月份大于等于3,则让总天数加1。
package Awork;
import java.util.Scanner;
/**
* @author : Jack
*/
public class WhichDay4 {
public static void main(String[] args) {
//题目:输入某年某月某日,判断这一天是这一年的第几天?
//1 2 3 4 5 6 7 8 9 10 11 12
//31 28 31 30 31 30 31 31 30 31 30 31
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int year = sc.nextInt();
System.out.println("请输入月份");
int month = sc.nextInt();
System.out.println("请输入日期");
int day = sc.nextInt();
int days;
switch(month) {
case 1:
days = day;
break;
case 2:
days = 31+day;
break;
case 3:
days = 31+28+day;
break;
case 4:
days = 31+28+31+day;
break;
case 5:
days = 31+28+31+30+day;
break;
case 6:
days = 31+28+31+30+31+day;
break;
case 7:
days = 31+28+31+30+31+30+day;
break;
case 8:
days = 31+28+31+30+31+30+31+day;
break;
case 9:
days = 31+28+31+30+31+30+31+31+day;
break;
case 10:
days = 31+28+31+30+31+30+31+31+30+day;
break;
case 11:
days = 31+28+31+30+31+30+31+31+30+31+day;
break;
default:
days = 31+28+31+30+31+30+31+31+30+31+30+day;
}
if( (year%4==0 && year%100!=0 || year%400==0) && month>=3 ) {
days++;
}
System.out.println("这是今年的第"+days+"天");
}
}
输出结果:
下一篇: 红黑树