輸入某年某月某日,判斷這一天是這一年的第幾天? – JAVA編程語言程序開發技術文章

import java.util.Scanner; 
 
/*輸入某年某月某日,判斷這一天是這一年的第幾天?   
1.程序分析:以3月5日為例,應該先把前兩個月的加起來,然後再加上5天即本年的第幾天,
特殊情況,閏年且輸入月份大於3時需考慮多加一天。*/ 
public class Day1 { 
    public static void main(String[]args){ 
        System.out.println("請輸入某年(例如:86年,請輸入:1986):"); 
        Scanner in = new Scanner(System.in); 
        int year = in.nextInt(); 
        System.out.println("請輸入某月(例如:1月,請輸入7):"); 
        int month = in.nextInt(); 
        System.out.println("請輸入某日(例如:1號,請輸入1):"); 
        int day = in.nextInt(); 
         
        int arr1[] = {31,28,31,30,31,30,31,31,30,31,30,31};//非閏年 
        int arr2[] = {31,29,31,30,31,30,31,31,30,31,30,31};//閏年 
         
        int tian = 0; 
        int zhengyue = 0; 
 
        if(year%100!=0&&year%4 == 0){ 
            if(month<2){ 
                System.out.println(year+"年"+month+"月"+day+"日是今年的第"+day+"天"); 
            }else{ 
                for(int i = 2;i <= month;i++){ 
                    zhengyue += arr2[i-2]; 
                } 
                tian = zhengyue + day; 
                System.out.println(year+"年"+month+"月"+day+"日是今年的第"+tian+"天");} 
             
        }else{ 
            if(month<2){ 
                System.out.println(year+"年"+month+"月"+day+"日是今年的第"+day+"天"); 
            }else{ 
                for(int i = 2;i <= month;i++){ 
                    zhengyue += arr1[i-2]; 
                } 
                tian = zhengyue + day; 
                System.out.println(year+"年"+month+"月"+day+"日是今年的第"+tian+"天"); 
                 
            } 
        } 
    } 

摘自 djw10962000的專欄

發佈留言