I'm practicing a bit of Java SE 7 on my own and came across the following problem. I've written a public static void function ValidDate that takes in three strings and only throws an assertion error if the date is not valid. ValidDate uses two string arrays (MONTHS and DAYS) as libraries to validate the given date. ValidDate also has a unique assert expression at the end of each assertion test:
public static void ValidDate(String month, String day, String year){
boolean validday = false;
boolean validmonth = false;
boolean validyear = true;
try{
Integer.parseInt(year);
}catch(NumberFormatException e){
validyear = false;
}
assert(validyear): "Error: year entry not written in integers.";
for(String m:MONTHS){
if(m.equals(month)){
validmonth = true;
}
}
assert (validmonth): "Error: month entry is not valid; must be an"
+ " integer between (0)1 and 12.";
...
}
My intent is to add ValidDate as a help function for a DOB setter (SetDOB) for my public class Person. The implementation would be to have ValidDate throw an exception when an invalid DOB is entered in the setter, and SetDOB would then output a message that the entered DOB was unacceptable and not change the current DOB value:
public void SetDOB(String newDOB){
String[] dates = newDOB.split("/");
boolean validdate = true;
if(dates.length == 3){
try{
ValidDate(dates[0],dates[1],dates[2]);
}
catch(AssertionError e){
System.out.println("Error: ValidDate threw an assert error.");
validdate = false;
}
if(validdate){
DOB = newDOB;
}
}
else{
System.out.println("Please enter a valid DOB of the form: Month/Day"
+ "/Year using integers.");
}
}
When I attempted to run SetDOB with an invalid DOB, however, ValidDate would not throw an AssertionError for SetDOB to catch. No error messages were output either. I suspect that the cause of this is related to my use of try-catch statements in either ValidDate or SetDOB. However, I may have made a different mistake without realizing it as well. I want someone to explain what I did wrong and how to accomplish my intended task correctly. If someone else has already answered this or a similar question, then please add in a link to their post. I may also remove this post if I find it redundant when encountering the linked post.