嗯,我正在与客户一起编写一个租车系统,这些客户都有身份证。在租车时,客户需要使用 id 来识别自己的身份,因此我需要一个自定义异常来处理用户输入的内容是否为 8 个数字和 1 个字母,例如:
55550000A
我已经对输入是否为 int 进行了异常(exception)处理,结果如下:
import java.util.*;
import java.util.Scanner;
public class read {
static Scanner leer=new Scanner(System.in);
public static int readInt() {
int num = 0;
boolean loop = true;
while (loop) {
try {
num = leer.nextInt();
loop = false;
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
System.out.println("Write again");
leer.next();
}
}
return num;
}
}
您唯一要做的就是声明变量并调用方法,如下所示:
int variable=read.readInt();
所以如果 id 可以像这样工作那就太好了,我的意思是另一个方法 readId() 它将返回该值。问题是我不知道如何对自定义格式进行异常(exception)处理,或者是否可能这样做,所以任何帮助都会有所帮助。非常感谢!
最佳答案
你的问题有点令人困惑,但我猜你想创建一个新的异常(exception)。
创建文件MyAppException.java
class MyAppException extends Exception {
private String message = null;
public MyAppException() {
super();
}
public MyAppException(String message) {
super(message);
this.message = message;
}
}
你可以通过以下方式扔它
throw new MyAppException();
但我想你想要的东西不需要异常(exception):
public static String readId() {
String id = "";
while(true){
id = leer.next();
try{
Integer.parseInt(id.substring(0,8));
}catch(InputMismatchException e){
System.out.println("Invalid Input");
continue;
}
if(id.length() != 9)continue;
if(Character.isLetter(id.chatAt(8)))break;
}
return id;
}
关于java - 自定义异常-Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211469/