首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用递归的简单阶乘程序

使用递归的简单阶乘程序
EN

Code Review用户
提问于 2014-09-17 11:03:22
回答 1查看 1.5K关注 0票数 5

我意识到需要理解和使用更多的两个概念是递归和异常。因此,我将两者结合在下面的程序中。虽然它从使用递归开始,但它更多地是关于异常的。我认为递归部分是赤裸裸和直截了当的,但我还是很欣赏关于使用/格式化递归的任何技巧/建议。

关于异常处理:以下是使用它们的最佳方式,还是有一种传统上更受欢迎的方式?我觉得我可能错过了做一些不必要的事情或者错过了一些重要的事情。

代码语言:javascript
运行
复制
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;
    }
}
EN

回答 1

Code Review用户

发布于 2014-09-17 12:00:22

@tim在回答中的困惑表明,您的代码可以使用注释:

代码语言:javascript
运行
复制
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;
}

我自己也很困惑。

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/63138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档