- /*
- 题目:输入某年某月,判断这一年与这一月分别距离1898年1月1日多少天?
- */
- import java.util.Calendar;
- import java.util.Scanner;
- class GetDay
- {
- public static void main(String[] args)
- {
- Scanner in = new Scanner(System.in);
- String str;
- System.out.println("请出入一个年月,中间用空格隔开,如2013 7 :");
- int year, month;
- while(true){
- str = in.nextLine();
- if(str.matches("\\d+ +[01]?\\d")){
- String[] strArr = str.split(" +");
- year = Integer.parseInt(strArr[0]);
- month = Integer.parseInt(strArr[1]);
- if(year > 0 || month > 0 || month < 13)
- break;
- }
- System.out.println("输入格式错误,请重新输入");
- }
- //输出结果
- System.out.println(year + "年距离1898年1月1日的天数为: " + getTotalDay(year) + "天");
- System.out.println(year + "年" + month + "月距离该年1月1日的天数为: " + getTotalDay_1(year,month) + "天");
-
- }
- //获取从某一年的1月1日距离1898年的天数
- public static int getTotalDay(int year){
- if(year == 1898)
- return 0;
- int smaller, bigger;
- if(year > 1898){
- smaller = 1898;
- bigger = year;
- }else{
- smaller = year;
- bigger = 1898;
- }
- int sum = 0;
- Calendar c = Calendar.getInstance();
- while(smaller < bigger){
- c.set(++smaller, 0, 1);
- c.add(Calendar.DAY_OF_MONTH, -1);
- sum += c.get(Calendar.DAY_OF_YEAR);
- }
- return sum;
- }
- //获取某月的第一天距离当年第一天有多少天
- public static int getTotalDay_1(int year, int month){
- int sum = 0;
- Calendar c = Calendar.getInstance();
- for(int i = 1; i < month; i++){
- c.set(year, i, 1);
- c.add(Calendar.DAY_OF_MONTH, -1);
- sum += c.get(Calendar.DAY_OF_MONTH);
- }
- return sum;
- }
- }
复制代码 |