Note that there are some explanatory texts on larger screens.

plurals
  1. POJAVA - Having trouble checking if a user input date is right
    text
    copied!<p>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. </p> <p>Heres the code for Main1 class:</p> <pre><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></pre> <p>}</p> <p>This is code for my own defined date class:</p> <pre><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); } // 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; } </code></pre> <p>I am also unsure if the code for the method checkInputs is right.</p> <p>EDIT: I have removed the IF statement as stated below in answers, Thank You. Just wanted to ask if there is anyway i can enforce the user to enter a four digit year YYYY always or it will keep looping until this happens</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload