好吧,我正在与客户一起编程租车系统,这些客户有身份证。租车时,客户需要使用ID识别自己的身份,因此我需要一个自定义异常,该异常可以处理用户输入的是8位数字和一个字母,例如:

55550000A


我已经对输入是否为int进行了例外处理:

   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()将返回该值。事实是,我不知道如何为自定义格式设置例外,或者是否有可能这样做,所以任何帮助都将有所帮助。非常感谢你!

最佳答案

您的问题有点混乱,但是我想您想创建一个新的例外。

创建一个文件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();


但是我想您不需要什么例外:

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;
}

07-25 22:28
查看更多