因此,我有一个程序可以接收来自用户的两个字母,并且如果这两个字母都不以U,C或P开头,则会引发错误。
到目前为止,我创建的代码可以正常工作,现在我想捕获异常,但继续处理来自用户的更多数据。
到目前为止,这是我的代码:
import java.util.Scanner;
public class Class113 {
public static void main(String[] args) {
// Declare scanner
Scanner scan = new Scanner(System.in);
// Display a message to instruct the user
System.out.println("Enter the designation: ");
// Receive input
String str = scan.next();
try{
// Verify str is not null and make sure UCP are capital letters whens ubmitted
if (str != null && (str.charAt(0) == 'U' || str.charAt(0) == 'C' || str.charAt(0) == 'P') && str.length() == 2) {
System.out.println("Valid designation");
} else{
throw new InvalidDocumentCodeException("Invalid designation. Designation must be two characters and start with U,C or P.");
}
} catch(InvalidDocumentCodeException invalidDocError){
System.out.println(invalidDocError);
}
}
}