1. 程式人生 > >JAVA 題目:輸入某年某月某日,判斷這一天是這一年的第幾天?

JAVA 題目:輸入某年某月某日,判斷這一天是這一年的第幾天?

再看 應該 boolean post pos tin als ini ror

 
1
package Training; 2 3 //import java.util.Calendar; 4 import java.util.Scanner; 5 /** 6 * 題目:輸入某年某月某日,判斷這一天是這一年的第幾天? 7 * 1.程序分析:以3月5日為例,應該先把前兩個月的加起來,然後再加上5天即本年的第幾天,特殊情況,閏年且輸入月份大於3時需考慮多加一天。 8 * @author MoRua 9 * @version 1.0 10 * 11 */ 12 13 public class Time11 { 14 15 public
static int getTime(boolean isLeap,int month,int day) throws Throwable { 16 int sum=0; 17 18 if(month>12||month<1||day>31||day<1) { 19 throw new Exception(" DAY ERROR"); 20 } 21 22 for(int i=1;i<=month;i++) { 23 switch
(i) { //1 3 5 7 8 10 12 -> 2 4 6 8 9 11 12+ 24 25 case 1: 26 sum+=0; 27 break; 28 29 case 2: 30 case 4: 31 case 6: 32 case 8: 33 case 9: 34 case 11: 35 if(day>30) { 36 throw
new Exception(" DAY ERROR"); 37 } 38 sum+=31; 39 break; 40 41 case 3: 42 if(isLeap){ 43 sum+=29; 44 } 45 else 46 sum+=28; 47 break; 48 49 case 5: 50 case 7: 51 case 10: 52 case 12: 53 sum+=30; 54 break; 55 56 default: 57 break; 58 } 59 } 60 sum+=day; 61 return sum; 62 } 63 64 public static boolean isLeapYear(int year) { 65 if((year%4==0&&year%100!=0)||year%400==0) 66 return true; 67 return false; 68 } 69 70 public static void main(String[] args) throws Throwable { 71 int year; 72 int month; 73 int day; 74 @SuppressWarnings("resource") 75 Scanner scanner = new Scanner(System.in); 76 year=scanner.nextInt(); 77 month=scanner.nextInt(); 78 day=scanner.nextInt(); 79 long startTime = System.currentTimeMillis(); 80 81 try { 82 System.out.println(" "+getTime(isLeapYear(year), month, day)); 83 } catch (Exception e) { 84 System.out.println(e.getMessage()); 85 } 86 87 88 // Calendar calendar=Calendar.getInstance(); 89 // calendar.set(year,month,day);//設置calendar的年月日 90 // int temp=calendar.get(Calendar.DAY_OF_YEAR);//得到當年第幾天 91 // System.out.println("你輸入的日期是當年第"+(temp)+"天"); 92 93 long endTime = System.currentTimeMillis(); 94 System.out.println("Time: "+(endTime-startTime)); 95 } 96 }

最近才開始練習JAVA,寫的很慢,但是想寫一個就寫好。

加了一些對輸入的判斷,保證輸入的正確性,和程序的安全性。

註釋裏面的代碼是從網上找到的,但是運行時不正確,好像是多加了一個當月的總天數。

 Calendar 這個對象 有空再看看吧。

JAVA 題目:輸入某年某月某日,判斷這一天是這一年的第幾天?