gpt4 book ai didi

java - 捕获 IllegalArgumentException?

转载 作者:行者123 更新时间:2023-12-02 05:15:48 31 4
gpt4 key购买 nike

我这里遇到了一点问题。我想弄清楚如何捕获 IllegalArgumentException。对于我的程序,如果用户输入负整数,程序应该捕获 IllegalArgumentException 并询问用户是否要重试。但是当抛出异常时,它不会提供该选项。它就这样终止了。我尝试使用 try 和 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 block 以继续循环的工作。一旦遇到非法参数异常,就会在 catch block 中捕获它并询问用户是否要继续

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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com