当我合并 try -catch 方法时,我希望我的阶乘输出一条打印出“无效错误。没有负数”的语句,但每次它都不打印我的错误语句。这是我的代码:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
int value;
//E.g. 4!=4*3*2*1
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter a value for factorial");
value=keyboard.nextInt();
try{
System.out.println(calculate(value));}catch(NumberFormatException e){
System.out.println("invalid error. No negative numbers");
}
}
private static int calculate(int value){
if(value==1 || value==0){
return 1;
}
return calculate(value-1)*value;
}
}
我做错了什么
最佳答案
你还没有抛出异常
private static int calculate(int value) throws NumberFormatException {
if (value < 0) throw new NumberFormatException("invalid error. No negative numbers");
if(value==1 || value==0){
return 1;
}
return calculate(value-1)*value;
}
关于java - try catch 阶乘递归函数的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40247020/