Date値をユーザーから文字列として取得した後、String to Dateを解析する際に例外がスローされます。 日付の値を格納するために実行する必要があるものは、日付を取得するための特定のメソッドがあります。コンストラクタを使用して日付値を取得し、日付型の変数に格納する
Medicine.java
package Medicine;
import java.util.Date;
public abstract class Medicine {
public int price;
Date expiryDate;
Medicine() {
}
Medicine(int price, Date expiryDate) {
this.price=price;
this.expiryDate=expiryDate;
}
public void getDetails() {
System.out.println("The price is "+this.price);
System.out.println("The expiry Date for the product is "+this.expiryDate);
}
abstract void displayLabel();
}
Tablet.java
package Medicine;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Tablet extends Medicine{
Date expDate;
void displayLabel() {
System.out.println("Store in a cool and dry place");
}
Tablet() {
}
Tablet(int price, Date expDate) {
this.price=price;
this.expDate=expDate;
}
}
実行クラス
int price;
Date expDate=new Date();;
Scanner reader = new Scanner(System.in);
Medicine[] medicineArray =new Medicine[5];
DateFormat df=new SimpleDateFormat("dd-mm-yyyy");
System.out.println("Enter Tablet's price");
price = reader.nextInt();
System.out.println("Enter Tablet's expiry date in yyyy-dd-mm format");
String stringExpDate=reader.nextLine();
try {
expDate=df.parse(stringExpDate);
}
catch(Exception e){
System.out.println("Date format not parsed");
}
Medicine med1=new Tablet(price,expDate);
med1.getDetails();
med1.displayLabel();
出力:
は
が解析されていない
日付形式YYYY-DD-MMの形式でタブレットの有効期限を入力し、タブレットの価格を入力
価格は23
満了日であります製品のヌルです
あなたも独自のコードを理解していますか? – Jay
はい@Jay。 YYYY-DD-MMの形式でタブレットの有効期限を入力し 日付形式 解析されていないタブレットの価格を入力します あなたはすでに私が手 –