希望你能仔细理解了之后自己写,加油!
首先:先判断是否闰年,在利用swtch()的break;得出每个偶数月份和奇数月份的出现的次数,然后相加,最后一定要加最后一个月的天数。
星期的判定是利用DateFormat和Data中的特有的方法;
- import java.io.*;
- import java.text.*;
- import java.util.Date;
- public class Test9 {
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- 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("月份输入错误");
- }
- //当前月天数
- day = Integer.valueOf(s.substring(6));
-
- //调用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 += 29;
- else dateSum1 += 28;
- }
- }
-
- return dateSum1+day;
- }
- }
复制代码 |