我在这里有点问题。我试图弄清楚如何捕获IllegalArgumentException。对于我的程序,如果用户输入一个负整数,则程序应捕获IllegalArgumentException并询问用户是否要重试。但是,当引发异常时,它不会提供该选项。它只是终止。我尝试使用try and catch方法,但对我不起作用。如何捕获此特殊异常以继续运行而不是终止?
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块中,并询问用户是否要继续
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);
}
}
}
}
}
希望这可以帮助。
快乐学习:)
关于java - 捕捉到IllegalArgumentException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26960941/