因此,我有一个程序可以接收来自用户的两个字母,并且如果这两个字母都不以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);
}
}
}
答案 0 :(得分:1)
只需使用while循环即可。
while(true)
实际上是无限的,但是您可以使用break
来摆脱它。
我使用"q"
作为表示退出程序的字符串,但是如果需要,您可以使用其他名称。
import java.util.Scanner;
class InvalidDocumentCodeException extends RuntimeException {
public InvalidDocumentCodeException(String s) {
super(s);
}
}
public class Class113 {
public static void main(String[] args) {
// the try here is called try with resource
// it will close the scanner at the end of the block.
try(Scanner scan = new Scanner(System.in)){
while(true){
// Display a message to instruct the user
System.out.println("Enter the designation: ");
// Receive input
String str = scan.next();
if(str.equals("q")) break;
try {
// Verify str is not null and make sure UCP are capital letters whens ubmitted
if (str.length() == 2 && (str.charAt(0) == 'U' || str.charAt(0) == 'C' || str.charAt(0) == 'P')) {
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);
}
}
}
}
}
除非您需要向程序的其他部分发送有关该错误的信号,否则在这里我不会使用异常。只需在else块中打印出来就足够了。