JAVA - Having trouble checking if a user input date is right

Adanialully

New Member
I have two classes, Main1 and a date (my own defined date class). I am trying to get user input of day, month and year, and then trying to check if this is a valid date using my date class. Im really confused and not sure if this is right way. Heres the code for Main1 class:\[code\]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);} \[/code\]}This is code for my own defined date class:\[code\]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); }// Methodspublic 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; }\[/code\]I am also unsure if the code for the method checkInputs is right.
 
Back
Top