简体   繁体   English

我该如何做一个do while循环并连续捕获异常?

[英]How can I make a do while loop with an exception catch, continuous?

I try to catch the exception which finally works but now I need to figure out how to make it loop. 我尝试捕获最终可以工作的异常,但是现在我需要弄清楚如何使其循环。 ALso, how would I be able to get user input(int select) to the outside of the loop? 另外,我如何能够将用户输入(int选择)带到循环的外部? I can try creating a new function, that might do the trick. 我可以尝试创建一个新功能,这可能会解决问题。

do {
    System.out.print("How many integers shall we compare? (Enter a positive integer): ");
    try {
        select = intFind.nextInt();
    } catch (InputMismatchException e) {
        // Display the following text in the event of an invalid input
        System.out.println("Invalid input!");
        intFind.nextLine();
    }
} while (select < 0);

Then 然后

do
            {
                System.out.print("How many integers shall we compare? (Enter a positive integer): ");
                try {
                    b = Get();
                }
                catch (InputMismatchException e) {
                    // Display the following text in the event of an invalid input
                    System.out.println("Invalid input!");

                    intFind.nextLine();
                } copySel = b;  
            }while(select < 0);

and

static int Get()
    {
        Scanner intFind = new Scanner(System.in);
        int select;
        select = intFind.nextInt();
        return select;
    }

To make it loop make sure that select is initialized to a value less than 0. But it would be better to have a condition select < 2 , because it makes more sense to compare at least to values. 要使其循环,请确保将select初始化为小于0的值。但是最好使条件select < 2更好,因为至少将其与值进行比较更有意义。

Create a method like 创建类似的方法

private int[] promptIntegers(int numberOfIntegers, Scanner sc) {
    int[] integers = new int[numberOfIntegers];
    //read ints
    //return the array
}

and call it like 并称它为

select = intFind.nextInt();
int[] integers = promptIntegers(select, sc);
//do the comparison among the integers

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

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