[英]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類。
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" ) ;
或者,分別要求輸入年、月和日。 將每個解析為 integer ,並將三個int
值傳遞給LocalDate.of
,如上所示。
提示:
我知道這是家庭作業,並且不允許您使用標准庫中的LocalDate
(就像在生產代碼中無條件地做的那樣)。
選項包括(但不限於):
Scanner.nextInt()
的三個調用依次將月、月和年的日期讀取為三個數字。 將這三個數字傳遞給您的Date
構造函數。Scanner.next()
或Scanner.nextLine()
從用戶那里讀取日期,例如29-05-2020
。 在連字符處拆分。 使用Integer.parseInt()
將每個數字解析為一個int
。 將三個解析的數字傳遞給構造函數。文檔鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.