I want to add a custom exception to validate the name
.That is name
should only accepts [a-zA-Z]
. If the name is invalid, user need to enter again. Help me to implement this.
public class EmployeeInfo {
static int next_id = 0;
int id;
static String name;
Date DoB, DoJ;
public void setName(final String name) {
this.id = ++EmployeeInfo1.next_id;
this.name = name;
}
public void setDateOfBirth(final Date DoB) {
this.DoB = DoB;
}
public void setDateOfJoining(final Date DoJ) {
this.DoJ = DoJ;
}
void print() {
System.out.println("User ID: " + id);
System.out.println("Name: " + name);
System.out.println("Date Of Birth: " + DoB);
System.out.println("Date of Joining: " + DoJ);
}
public static Date checkDate(final String dt) throws ParseException {
final SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
final SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
final SimpleDateFormat sdf3 = new SimpleDateFormat("dd MMMM yyyy");
Date date = null;
try {
date = (Date) sdf1.parse(dt);
} catch (final ParseException e) {
try {
date = (Date) sdf2.parse(dt);
} catch (final ParseException e1) {
try {
date = (Date) sdf3.parse(dt);
} catch (final ParseException e2) {
final String invalid = "Invalid Date Format,Re-enter!";
System.out.println(invalid);
}
}
}
return date;
}
public static void main(final String[] args) throws ParseException {
final Scanner scanner = new Scanner(System.in);
final EmployeeInfo1 e = new EmployeeInfo1();
System.out.println("Enter the name: ");
e.setName(scanner.nextLine());
Date d = null;
while (d == null) {
System.out.println("Enter the Date Of Birth: ");
d = checkDate(scanner.nextLine());
}
e.setDateOfBirth(d);
d = null;
while (d == null) {
System.out.println("Enter the Date of Joining: ");
d = checkDate(scanner.nextLine());
}
e.setDateOfJoining(d);
e.print();
}
}