Java int的三个例外

Java int的三个例外,java,exception,Java,Exception,我试图创建一个代码,其中应该输入一个int,如果int不在9和99之间,则会出现异常;如果输入的是double而不是int,则会出现另一个异常;如果输入的是字符串,则会出现第三个异常。我该怎么做?我有以下我到目前为止,但不知道如何纠正它。谢谢 public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean correct = true; do {

我试图创建一个代码,其中应该输入一个int,如果int不在9和99之间,则会出现异常;如果输入的是double而不是int,则会出现另一个异常;如果输入的是字符串,则会出现第三个异常。我该怎么做?我有以下我到目前为止,但不知道如何纠正它。谢谢

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean correct = true;
    do {
        try {
            System.out.println("Enter an Integer between 9 and 99");
            int number = input.nextInt();
            if (number >= 9 && number <= 99) {
                System.out.println("Thank you, Initialization completed");
                correct = false;
            } else if (number < 9 || number > 99) {
                throw new Exception("Integer is not within the range");
            }
            if (input.hasNextDouble()) {
                throw new Exception("Integer not entered");
            } else {
                correct = false;
            }
            if (input.hasNext("")) {
                throw new NumberFormatException("Integer not entered");
            } else {
                correct = false;
            }
        } // check for range
        catch (Exception e1) {
            System.out.println("Number is not within 9 and 99");
            System.out.println();
            input.nextLine();
        } catch (Exception e2) {
            System.out.println("An integer was not entered");
            System.out.println();
            input.nextLine();
        } catch (NumberFormatException e3) {
            System.out.println("An integer was not entered");
            System.out.println();
            input.nextLine();
        }
    } while (correct);
}
publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(System.in);
布尔正确=真;
做{
试一试{
System.out.println(“输入一个介于9和99之间的整数”);
int number=input.nextInt();
如果(编号>=9&&99){
抛出新异常(“整数不在范围内”);
}
if(input.hasNextDouble()){
抛出新异常(“未输入整数”);
}否则{
正确=错误;
}
if(input.hasNext(“”){
抛出新的NumberFormatException(“未输入整数”);
}否则{
正确=错误;
}
}//检查范围
捕获(异常e1){
System.out.println(“数字不在9和99之间”);
System.out.println();
input.nextLine();
}捕获(异常e2){
System.out.println(“未输入整数”);
System.out.println();
input.nextLine();
}捕获(NumberFormatException e3){
System.out.println(“未输入整数”);
System.out.println();
input.nextLine();
}
}而(正确),;
}
方法。getMessage()返回构造函数中给定的字符串:

throw new Exception("HERE");
当您捕获异常时,还捕获NumberFormatException、InputMismatchException等。 所以你必须最后抓住更大的

catch (NumberFormatException e3) { // Precisier goes first
    System.out.println("An integer was not entered");
    System.out.println();
    input.nextLine();
}
catch (Exception e1) {
    System.out.println(e1.getMessage());
    System.out.println();
    input.nextLine();
}