简体   繁体   English

尝试捕获异常没有按预期工作

[英]Try Catch Exception not working as intended to be

My InputMismatchException won't work.我的InputMismatchException不起作用。 Instead the one working is the exception I manually made from the other class called InvalidLetterException .相反,一个工作是我从另一个名为InvalidLetterException类手动创建的异常。 If I enter a number the exception doing the catch is the InvalidLetterException instead of the InputMismatchException because I'm entering an integer, a different data type.如果我输入一个数字,则捕获的异常是InvalidLetterException而不是InputMismatchException因为我输入的是一个整数,一种不同的数据类型。 I'm hinting there's a problem with my if-else statement but I don't know what to do.我在暗示我的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.");
    }



}

Well, an InputMismatchException can never be thrown within your try block.好吧, InputMismatchException永远不会在您的try块中抛出。 If you would have called nextInt() instead, then it would.如果您改为调用nextInt() ,那么它会。 But next() does not expect the input to be in a certain format, you can enter whatever you want.但是next()并不期望输入是某种格式,你可以输入任何你想要的。

!answer.equals(choices)

This is always true if the other if statements are false, so effectively, it can be replaced by just else .如果其他if语句为假,则始终为真,因此可以有效地将其替换为else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM