我有两个类,Main1 和一个日期(我自己定义的日期类)。我正在尝试获取用户输入的日期、月份和年份,然后尝试使用我的日期类检查这是否是有效日期。我真的很困惑,不确定这是否正确。
这是 Main1 类的代码:
public class Main1 {
public static void main(String[] args){
int myDay = 0, myMonth = 0, myYear = 0;
boolean dataCorrect = false;
date travelDate; // travelDate will hold the date entered
do {
try {
do {
myDay = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the day: "));
myMonth = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the month: "));
myYear = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the year: "));
travelDate = new date(myDay,myMonth,myYear);
} while (travelDate.checkInputs(travelDate.formDate()) == false); // keeps looping until the date entered is correct
dataCorrect = true;
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error! Enter a correct date");
}
} while (dataCorrect == false);
JOptionPane.showMessageDialog(null, myDay + "-" + myMonth + "-" + myYear);
}
}
这是我自己定义的日期类的代码:
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class date {
private int day;
private int month;
private int year;
private String userTravel;
// Constructor
public date(int d, int m, int y) {
setDate(d,m,y);
}
// Methods
public void setDate(int d, int m, int y) {
setDay(d);
setMonth(m);
setYear(y);
}
public String formDate() {
userTravel = day + "-" + month + "-" + year;
return userTravel;
}
public boolean checkInputs(String inDate) {
if (inDate == null)
return false;
//set the format to use as a constructor argument
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
if (inDate.trim().length() != dateFormat.toPattern().length())
return false;
dateFormat.setLenient(false);
try {
//parse the inDate parameter
dateFormat.parse(inDate.trim());
}
catch (ParseException pe) {
return false;
}
return true;
}
public void setDay(int d) {
day = d;
}
public void setMonth(int m) {
month = m;
}
public void setYear(int y) {
year = y;
}
我也不确定方法 checkInputs 的代码是否正确。
编辑:我已经删除了答案中所述的 IF 语句,谢谢。只是想问是否有无论如何我可以强制用户输入一个四位数的年份 YYYY 或者它会一直循环直到发生这种情况