我意识到需要理解和使用更多的两个概念是递归和异常。因此,我将两者结合在下面的程序中。虽然它从使用递归开始,但它更多地是关于异常的。我认为递归部分是赤裸裸和直截了当的,但我还是很欣赏关于使用/格式化递归的任何技巧/建议。
关于异常处理:以下是使用它们的最佳方式,还是有一种传统上更受欢迎的方式?我觉得我可能错过了做一些不必要的事情或者错过了一些重要的事情。
import javax.swing.JOptionPane;
class FactorialDemo {
public static void main(String[] args) {
int factorialNumber = 0;
try {
factorialNumber = Integer.parseInt(JOptionPane.showInputDialog(null,
"Which number should we compute the factorial of?"));
} catch(NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be an integer!",
"Error", JOptionPane.ERROR_MESSAGE);
throw new NumberFormatException("Input must be an integer.");
}
JOptionPane.showMessageDialog(null,
factorialNumber + " factorial is " +recur(factorialNumber) +".",
"Result", JOptionPane.PLAIN_MESSAGE);
}
public static int recur(int n) {
int result;
if (n < 0) {
JOptionPane.showMessageDialog(null,"n must be >= 0 but was " + n,
"Error", JOptionPane.ERROR_MESSAGE);
throw new IllegalArgumentException("n must be >= 0 but was " + n);
}
if (n < 2) {
return 1;
}
result = recur(n - 1) * n;
return result;
}
}
发布于 2014-09-17 04:00:22
@tim在回答中的困惑表明,您的代码可以使用注释:
public static int recur(int n) {
int result;
if (n < 0) {
JOptionPane.showMessageDialog(null,"n must be >= 0 but was " + n,
"Error", JOptionPane.ERROR_MESSAGE);
throw new IllegalArgumentException("n must be >= 0 but was " + n);
}
if (n < 2) {//both 0! and 1! are 1
return 1;
}
result = recur(n - 1) * n;
return result;
}
我自己也很困惑。
https://codereview.stackexchange.com/questions/63138
复制