-1

我是编程新手(正在学习计算机科学课程),其中一个练习是让程序读取日期,然后一遍又一遍地打印接下来的 30 天,直到年底。

问题是,有限制。我不能使用 Date/Calendar 类,只能使用 Scanner 类。所以我在确定日期时遇到了一些麻烦......所以我发现的唯一方法是使用 Switch 并且每个月都有一个案例,但是 30/31 天的月份和闰年存在问题. 所以日子也不一样。

有没有更简单的方法来做到这一点?

4

2 回答 2

0

如果你不能使用日期/日历类,那么问题的目的是让你做日期/日历类在内部做的事情。看到 switch 语句作为您答案的一部分,我不会感到惊讶。你需要教你的实现知道一个月有多少天,哪些年份是闰年等等。

于 2013-06-14T14:03:56.890 回答
0

你可以使用这样的东西,

主类:

public class AppMain {

  public static void main(String[] args) {
    MyDate initDate = new MyDate(14, 1, 2012);
    printMyDate(initDate);

    MyDate newDate = initDate;

    do{
      newDate = DateIncrementator.increaseDate(newDate, 30);
      printMyDate(newDate);
    }while(newDate.getYear() == initDate.getYear());

  }

  private static void printMyDate(MyDate date){
    System.out.println("[Day: "+ date.getDay() + "][" + "[Mont: "+ date.getMonth() + "][" + "[Year: "+ date.getYear() + "]");
  }
}

日期增量器类:

public class DateIncrementator {
  private static final int[] MONTH_DAYS_NOP_LEAP_YEAR = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  public static MyDate increaseDate(MyDate date, int numberOfDays){
    if(numberOfDays < 1 || numberOfDays > 30){
      throw new IllegalArgumentException("numberOfDays must have a value between 1 and 30");
    }

    int numberDaysCurrentMonth = MONTH_DAYS_NOP_LEAP_YEAR[date.getMonth() - 1];

    if(date.getMonth() == 2 && isLeapYear(date.getYear())){
      numberDaysCurrentMonth++;
    }

    int newDay = date.getDay();
    int newMonth = date.getMonth();
    int newYear = date.getYear();

    newDay += numberOfDays;

    if(newDay > numberDaysCurrentMonth){
      newDay = newDay % numberDaysCurrentMonth;
      newMonth++;
    }

    if(newMonth > 12){
      newMonth = 1;
      newYear++;
    }

    return new MyDate(newDay, newMonth, newYear);
  }

  private static boolean isLeapYear(int year){
    if(year % 4 != 0){
      return false;
    }

    if(year % 100 != 100){
      return true;
    }

    if(year % 400 == 0){
      return true;
    }else{
      return false;
    }
  }
}

MyDate 类:

public class MyDate {
  private int day; // 1 to 31
  private int month; // 1 to 12
  private int year; // 0 to infinite


  public MyDate(int day, int month, int year) {
    this.day = day;
    this.month = month;
    this.year = year;
  }

  public int getDay() {
    return day;
  }

  public int getMonth() {
    return month;
  }

  public int getYear() {
    return year;
  }  
}
于 2013-06-14T15:21:05.797 回答