使用我自己的日期作为用户输入的日期 class

Date as a user input using my own Date class

我正在开发一个应用程序,在那里我必须从用户那里获取日期,而且它只是日期,不需要时间。我被要求使用 Date class 来表示日期。但是我不知道如何使用扫描仪从用户那里获取日期作为正常输入 class.

日期class如下所示,那么如何获取输入的日期呢?

我是编程新手,请帮我解决这个问题。

public class Date {

    private int day;
    private int month;
    private int year;

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

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    @Override
    public String toString() {
        return "Date{" +
                "day=" + day +
                ", month=" + month +
                ", year=" + year +
                '}';
    }
}

这是一个作业,它要求我们像这样实现一个Date class,它要求我们避免使用Java中的任何预定义库。

java.time.LocalDate

我们有一个 class:LocalDate。不要重新发明轮子。

请注意,日期时间处理是一项非常棘手的工作——不要尝试自己动手解决。始终使用行业领先的 java.time classes.

LocalDate ld = LocalDate.of( 2021 , 1 , 23 ) ;  // January 23, 2021.
String output = ld.toString() ;

2021-01-23

在控制台应用程序中,使用 Scanner class,要求用户输入 ISO 8601 格式 YYYY-MM-DD 的日期。

LocalDate ld = LocalDate.parse( "2021-01-23" ) ;

或者,要求分别输入年月日。 Parse each as an integer,并将三个 int 值传递给 LocalDate.of,如上所示。

提示:

  • 组织你的思维和代码,先在更大的范围内工作,然后在详细的范围内工作。所以年-月-日而不是日-月-年。
  • 了解 ISO 8601 交换数据时将日期时间值格式化为文本的标准。
  • 学习java.timetutorial by Oracle.

我知道这是家庭作业,你不能使用标准库中的 LocalDate(就像在生产代码中无条件地做的那样)。

选项包括(但不限于):

  1. 使用对 Scanner.nextInt() 的三次调用,将月、月和年作为三个数字依次读取。将这三个数字传递给您的 Date 构造函数。
  2. 使用 Scanner.next()Scanner.nextLine() 从用户那里读取日期,例如 29-05-2020。在连字符处拆分。使用 Integer.parseInt() 将每个数字解析为 int。将三个解析的数字传递给构造函数。

文档链接: