【发布时间】:2017-08-09 06:01:22
【问题描述】:
我想添加一个自定义异常来验证name。即name 应该只接受[a-zA-Z]。如果名称无效,用户需要重新输入。帮我实现这个。
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();
}
}
【问题讨论】:
-
您希望得到什么样的帮助?
-
帮我添加自定义异常..
-
创建一个自定义异常类,如:class AlsCustomException extends Exception { public AlsCustomException(String message) { super(message); } }
-
欢迎来到 Stack Overflow!请take the tour 了解该网站的运作方式以及此处的主题问题,并相应地编辑您的问题。另见:Why is "Can someone help me?" not an actual question?
标签: java validation exception