在java中輸入某年某月,判斷這一天是是這一年的第多少天
阿新 • • 發佈:2019-02-02
在java中輸入某年某月,判斷這一天是這一年的第多少天
對於這個問題,首先應該想到的閏年和非年年的之間的差別,基月和偶月的之間的差別,
具體看看程式設計怎麼實現把:
package excise; import java.util.Scanner; public class T011 { public static void main(String args[]) { boolean b = true; while (b) { System.out.println("請輸入年份:"); Scanner s = new Scanner(System.in); long date = s.nextLong(); String string_year = String.valueOf(date); int year = Integer.parseInt(string_year.substring(0, 4)); int month = Integer.parseInt(string_year.substring(4, 6)); int day = Integer.parseInt(string_year.substring(6)); if ((month < 1 || month > 12) || (day < 1 || day > 31)) { System.out.println("輸入年份有錯誤,請重新輸入"); b = true; } else { System.out.println("年份輸入正確"); b = false; System.out.println("輸入的年份"+date+"是該年的第"+caculate(year,month,day)+"天"); } } } public static int caculate(int year,int month,int day){ int days = 0; for(int i=1;i<month;i++){ switch(i){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: days=31; break; case 4: case 6: case 9: case 11: days=30; break; case 2: if((year%400==0)||(year%4==0)||(year%100!=0)){ days=29; }else{ days=28; } break; default: break; } day+=days; } return day; } }