------- <a href="http://www.itheima.com" target="blank">android培訓</a>、<a href="http://www.itheima.com" target="blank">java培訓</a>、期待與您交流! ----------
package com.itheima;
/***編寫程序,該程序啓動後用戶可以按“yyyy-MM-dd”的格式輸入一個日期,
*程序計算這一天是星期幾,並且計算出是一年中的第幾天。
*/
import java.io.*;
import java.text.*;
import java.util.Date;
public class Test9 {
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("開始輸入日期:");
int month = 0,day = 0;
long year = 0;
//從鍵盤讀取數據,建立轉換流
BufferedReader bf =
new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(System.out));
String s = null;
StringBuffer sb = new StringBuffer();
while((s = bf.readLine())!=null){
//年數
year = Integer.valueOf(s.substring(0,4));
if(Integer.valueOf(s.substring(4,5)) == 0){
//月數
month = Integer.valueOf(s.substring(5,6));
}
else{
if(Integer.valueOf(s.substring(4,6)) <= 12)
month = Integer.valueOf(s.substring(4,6));
else
System.out.println("月份輸入錯誤");
}
//當前月天數
if( Integer.valueOf(s.substring(6))<31)
{
day = Integer.valueOf(s.substring(6));
}
else{System.out.println("你輸入的天數有錯");}
//調用Day方法算出天數
System.out.println(year+"年"+month+"月"+day+"日");
System.out.println("第"+Day(year,month,day)+"天");
WeekDay(s);
}
}
public static void WeekDay(String day){
String[] str ={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
DateFormat df = new SimpleDateFormat("yyyyMMdd");//日期格式化輔助類
Date d = new Date();
try{
d = df.parse(day);//格式化日期
}catch(ParseException e){
e.printStackTrace();
}
for(int i=0;i<str.length;i++){
if(d.getDay()==(i)) //根據取出來的數判斷取數組下標
{
System.out.println(str[i]);
}
}
}
public static int Day(long year,int month,int day){
int dateSum1 = 0;
for (int i = 1; i < month; i++){
switch(i){
//當月份爲1,3,5,7,8,,10,12時,自動加31天
case 1: case 3: case 5: case 7: case 8: case 10:
case 12:dateSum1 += 31; break;
//當月份爲4,6,9,11時,自動加30天
case 4: case 6: case 9: case 11:dateSum1 += 30; break;
case 2:
// 判斷是否爲閏年,如果是加29,否加28
if(( (year % 4 == 0) & (year % 100 != 0)) | (year % 400 == 0)| dateSum1<30)
dateSum1 += 29;
else dateSum1 += 28;
}
}
return dateSum1+day;
}
}
------- <a href="http://www.itheima.com" target="blank">android培訓</a>、<a href="http://www.itheima.com" target="blank">java培訓</a>、期待與您交流! ----------