Java Eclipse Scanner Date



我只是在做一个有趣的程序。

所以在我的程序中,我想创建一个启动促销函数,当使用它时,我们可以写促销日期,即dd/MM/yyyy。但我很困惑,不知道如何让他扫描。


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
Scanner scan = new Scanner (System.in);
Date date = new Date();
SimpleDateFormat DateFormat = new SimpleDateFormat("dd/MM/yyyy");
private void NewClothPromo() {
String type;
Date startpromo;
do {
System.out.print("Input Cloth Type [Shirt | Pants] (case sensitive): ");
type = scan.next();
}while(type.compareTo("Shirt")!=0&&type.compareTo("Pants")!=0);
do {
System.out.print("Input Start Promo Date [dd/MM/yyyy]: ");
startpromo = ......
}while(startpromo.equals(DateFormat));
do {
System.out.print("Input Start Promo Date [dd/MM/yyyy]: ");
startpromo = ......
}while(startpromo.equals(DateFormat));

提前谢谢你

你这样做是不对的。始终将来自用户的日期类型输入作为String,然后将其转换为Date实例。如:

try{
System.out.println("Input : ");
String input = scan.nextLine();
//parsing the date in desired format if input pattern is ok then it will parse other wise will throw exception
startpromo = DateFormat.parse(input);
}catch(ParseException e){
e.printStackTrace();
}

do-while检查startpromo是否为空

使用while的例子:

while(startpromo==null){
//taking input and convertion
}

建议尝试使用java.time作为日期时间实例,因为util.date已经过时了。格式化的所有概念都是相同的,除了使用另一个包。

下面是你的例子:

LocalDate  date = null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
while(date==null){
try{
System.out.println("Input : ");
String input = scan.nextLine();
//parsing the date in desired format if input pattern is ok then it will parse other wise will throw exception
date = LocalDate.parse(input,formatter);
}catch(DateTimeParseException e){
e.printStackTrace();
}
}

最新更新