首页 > 解决方案 > 尝试 Catch Exception 未按预期工作

问题描述

我的InputMismatchException行不通。相反,一个工作是我从另一个名为InvalidLetterException. 如果我输入一个数字,则执行 catch 的异常InvalidLetterException不是 the,InputMismatchException因为我输入的是一个整数,一种不同的数据类型。我暗示我的if-else陈述有问题,但我不知道该怎么做。

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    String questions[] = {"What is the color of the sky? ", "What is 1 + 1? ",
            "What is the capital of the Philippines? ", "Who is the current president of the Philippines? ",
            "What is the capital of Japan? ", "What is 2 + 3? ",
            "What is 9 + 1?", "What is the capital of the United States? ",
            "What is 10 + 10? ", "How many hand fingers do humans have? "};

    String choices[] = {"a","b","c"};


    int x = 0;
    int y = 0;



    try {

        while(x<=9) {

            System.out.println("No." + (x+1) + "." + questions[x]);
            String answer = scan.next();
            x++;

            if(answer.equals(choices[0])) {
                scan.nextLine();

            } else if (answer.equals(choices[1])) {
                scan.nextLine();

            } else if (answer.equals(choices[2])) {
                scan.nextLine();

            } else if (!answer.equals(choices)) {
                throw new InvalidLetterException(); 


            }

        } 

    } catch(InvalidLetterException e) {
        System.out.println(e.getMessage());
        System.out.println(); //Spacing
        System.out.println("You can try again.");
        System.out.println(); //Spacing
        do {
            System.out.println("No." + (y+1) + "." + questions[y]);
            scan.next();
            y++;
        }while(y<=9);

    } catch (InputMismatchException i) {
        System.out.println("Please don't enter numbers.");
    }



}

标签: java

解决方案


好吧,InputMismatchException永远不能在你的try街区内抛出一个。如果你会打电话nextInt(),那么它会。但next()不要期望输入是某种格式,你可以输入任何你想要的。

!answer.equals(choices)

如果其他陈述是错误的,这总是正确的if,因此有效地,它可以被替换为 just else


推荐阅读