简体   繁体   English

不能多次捕获异常

[英]cannot catch the exception more than one time

when running the code, if I input any character other than number, the exeception "java.util.InputMismatchException" gets catched, but next time if I input any character other than number, the program gets terminated with error "Exception in thread "main" java.util.InputMismatchException". 在运行代码时,如果我输入数字以外的任何字符,则将捕获“ java.util.InputMismatchException”,但是下次如果我输入数字以外的其他字符,则程序将终止,并出现错误“线程异常”。 “ java.util.InputMismatchException”。 how to make it able to catch more than one simultaneous exceptions untill a valid input is given. 如何使它能够捕获多个并发异常,直到给出有效输入为止。

/*
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
 */
import java.util.Scanner;

public class StudentPoll 
{
    static Scanner input=new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.println("Rate the quality of food from 1 to 5." +
                "\n1 being “awful” and 5 being “excellent”.\n");
        int[] array=new int[10];
        int num =0;
        for(int i=0;i<array.length;i++)
        {

            do{
                System.out.println("Student "+(i+1)+" Enter Your Response:");
                try
                {
                    num=input.nextInt();
                }
                catch(java.util.InputMismatchException e)
                {
                    System.out.println("Enter numbers only.");
                    input.nextLine();
                    num=input.nextInt();
                }   
                if(num<=0 || num>5)

                {
                    System.out.println("Enter 1 to 5 only.");
                }
            }while(num<=0 || num>5);
            array[i]=num;

        }

        int[] frequency=new int[6];

        for ( int i = 0; i < array.length; i++ )
        {
            frequency[array[i]]=frequency[array[i]]+1;      
        }

        System.out.printf("*    :%d (awful)\n",frequency[1]);
        System.out.printf("**   :%d\n",frequency[2]);
        System.out.printf("***  :%d\n",frequency[3]);
        System.out.printf("**** :%d\n",frequency[4]);
        System.out.printf("*****:%d (excellent)\n",frequency[5]);
    }
}`

Because you do not have another try-catch statement in your catch statement, you can just re-run the loop if you want to catch the exception again. 由于catch语句中没有其他try-catch语句,因此,如果要再次捕获该异常,可以重新运行循环。 So you would replace: 因此,您将替换为:

catch(java.util.InputMismatchException e)
{
    System.out.println("Enter numbers only.");
    input.nextLine();
    num = input.nextInt();
} 

with: 与:

catch(java.util.InputMismatchException e)
{
    System.out.println("Enter numbers only.");
    input.nextLine();
    continue;
}

Because when first exception occur in the try block that is caught by the catch block. 因为在try块中发生第一个异常时,该异常才由catch块捕获。 And if the user again give a invalid input then again the exception thrown. 如果用户再次输入无效的输入,则会再次引发异常。 But there is no mechanism in your code to catch that exception. 但是您的代码中没有机制可以捕获该异常。 Therefore the main thread stopped. 因此主线程停止了。 Catch block will not responsible to catch exception that is throw inside that block. 捕获块将不负责捕获在该块内引发的异常。

import java.util.Scanner;

public class StudentPoll
{
static Scanner input=new Scanner(System.in);
public static void main(String[] args)
{
    System.out.println("Rate the quality of food from 1 to 5." +
            "\n1 being “awful” and 5 being “excellent”.\n");
    int[] array=new int[10];
    int num =0;
    for(int i=0;i<array.length;i++)
    {

        do{
            System.out.println("Student "+(i+1)+" Enter Your Response:");
            try
            {
                num=input.nextInt();
            }
            catch(java.util.InputMismatchException e)
            {
                input.next(); // consume the leftover new line
                System.out.println("Enter numbers only.");
            }
            if(num<=0 || num>5)

            {
                System.out.println("Enter 1 to 5 only.");
            }

        }while(num<1 || num>5); // change in the logic
        array[i]=num;

    }

    int[] frequency=new int[6];

    for ( int i = 0; i < array.length; i++ )
    {
        frequency[array[i]]=frequency[array[i]]+1;
    }

    System.out.printf("*    :%d (awful)\n",frequency[1]);
    System.out.printf("**   :%d\n",frequency[2]);
    System.out.printf("***  :%d\n",frequency[3]);
    System.out.printf("**** :%d\n",frequency[4]);
    System.out.printf("*****:%d (excellent)\n",frequency[5]);
}
}  

Your Problem statements is after the wrong input the program doesn't wait for next user input You can achieve this my accepting the input via java.util.Scanner & making for loop within do while. 您的问题语句是在输入错误后程序不会等待下一个用户输入。您可以通过java.util.Scanner接受输入并在do while内进行for循环来实现此目的。

try the below code it should work as per your need. 试试下面的代码,它应该可以根据您的需要工作。

/*
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
 */
import java.util.Scanner;

public class StudentPoll  {
    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Rate the quality of food from 1 to 5."
                + "\n1 being “awful” and 5 being “excellent”.\n");
        int[] array = new int[10];
        int num = 0;

        do {
            for (int i = 0; i < array.length; i++) {
                System.out.println("Student " + (i + 1)
                        + " Enter Your Response:");
                Scanner sc = new Scanner(System.in);
                try {
                    num = sc.nextInt();
                } catch (java.util.InputMismatchException e) {
                    System.out.println("Enter numbers only.");
                    num = 0;
                    --i;
                    continue;
                }
                if (num <= 0 || num > 5) {
                    System.out.println("Enter 1 to 5 only.");
                    num = 0;
                    --i;
                    continue;
                }
                array[i] = num;
            }
        } while (num <= 0 || num > 5);


        int[] frequency = new int[6];

        for (int i = 0; i < array.length; i++) {
            frequency[array[i]] = frequency[array[i]] + 1;
        }

        System.out.printf("*    :%d (awful)\n", frequency[1]);
        System.out.printf("**   :%d\n", frequency[2]);
        System.out.printf("***  :%d\n", frequency[3]);
        System.out.printf("**** :%d\n", frequency[4]);
        System.out.printf("*****:%d (excellent)\n", frequency[5]);
    }
}

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

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