赶上IllegalArgumentException吗? [英] Catching IllegalArgumentException?

查看:36
本文介绍了赶上IllegalArgumentException吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有点问题.我试图弄清楚如何捕获IllegalArgumentException.对于我的程序,如果用户输入一个负整数,则程序应捕获IllegalArgumentException并询问用户是否要重试.但是,当引发异常时,它不会提供该选项.它只是终止.我尝试使用try and catch方法,但对我不起作用.如何捕获此特殊异常以继续运行而不是终止?

I am having a little bit of a problem here. I am trying to figure out how to catch the IllegalArgumentException. For my program, if the user enters a negative integer, the program should catch the IllegalArgumentException and ask the user if he/she wants to try again. But when the exception is thrown, it doesn't give that option. It just terminates. I tried to use the try and catch method but it doesn't work for me. How do I catch this particular exception to continue to run instead of terminating?

public static void main(String[] args) throws IllegalArgumentException
{
    String keepGoing = "y";
    Scanner scan = new Scanner(System.in);
    while(keepGoing.equals("y") || keepGoing.equals("Y"))
    {
        System.out.println("Enter an integer: ");
        int val = scan.nextInt();
        if (val < 0)
        {
            throw new IllegalArgumentException
            ("value must be non-negative");
        }
        System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
        System.out.println("Another factorial? (y/n)");
        keepGoing = scan.next();
    }
}

}

public class MathUtils
{
    public static int factorial(int n)
    {
        int fac = 1;
        for(int i = n; i > 0; i--)
        {
            fac *= i;
        }
        return fac;
    }
}

推荐答案

您需要在循环内添加try catch块,以继续进行循环工作.一旦遇到非法参数异常,将其捕获到catch块中,并询问用户是否要继续

You need to add the try catch block inside the loop to continue the working for the loop. Once it hits the illegal argument exception catch it in catch block and ask if the user wants to continue

import java.util.Scanner;

public class Test {
public static void main(String[] args) 
{
String keepGoing = "y";
populate(keepGoing);

}

static void populate( String keepGoing){
  Scanner scan = new Scanner(System.in);
 while(keepGoing.equalsIgnoreCase("y")){
     try{
        System.out.println("Enter an integer: ");
        int val = scan.nextInt();
        if (val < 0)
        {
            throw new IllegalArgumentException
            ("value must be non-negative");
        }
        System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
        System.out.println("Another factorial? (y/n)");
        keepGoing = scan.next();
    }
    catch(IllegalArgumentException i){
        System.out.println("Negative encouneterd. Want to Continue");
        keepGoing = scan.next();
        if(keepGoing.equalsIgnoreCase("Y")){
        populate(keepGoing);
        }
    }
    }
}
}

希望这会有所帮助.快乐学习:)

Hope this helps. Happy Learning :)

这篇关于赶上IllegalArgumentException吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆