【问题标题】:How can I make a do while loop with an exception catch, continuous?我怎样才能做一个带有异常捕获的while循环,连续的?
【发布时间】:2012-11-13 05:07:57
【问题描述】:

我试图捕捉最终有效的异常,但现在我需要弄清楚如何让它循环。另外,我怎样才能让用户输入(int select)到循环之外?我可以尝试创建一个新函数,这可能会成功。

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);

然后

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);

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

【问题讨论】:

  • 您希望用户输入一个正整数,但 while 子句中的条件检查小于零的数字。

标签: java loops do-while


【解决方案1】:

要使其循环,请确保将 select 初始化为小于 0 的值。但最好有条件 select &lt; 2,因为至少与值进行比较更有意义。

创建一个类似的方法

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

然后这样称呼它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2022-12-18
    • 2012-02-27
    • 2020-03-11
    • 1970-01-01
    相关资源
    最近更新 更多