如何使用此代码使Java递归?

时间:2011-04-02 06:42:01

标签: java recursion

我的代码可以输出素数,但此程序使用trycatch。你能帮我用递归改变这个程序吗?

package file;

import javax.swing.JOptionPane;

public class Snake {

    private static int getNilai(int number, int index) {
        if (index == 1)
            return 1;
        else if (number % index == 0)
            return 1 + getNilai(number, --index);
        else
            return 0 + getNilai(number, --index);
    }

    public static boolean cekPrime(int num) {
        if (num > 1)
            return (getNilai(num, num) == 2);
        else
            return false;
    }

    public static void main(String[] args) {
        while (true) {
            try {
                int n = Integer.parseInt(JOptionPane
                .showInputDialog("Enter your number!"));
                if (n > 0) {
                    int a = 0;
                    int b = 0;
                    int p[] = new int[n * n];
                    while (b < (n * n)) {
                        if (cekPrime(a)) {
                            p[b] = a;
                            b++;
                        }
                        a++;
                    }
                    for (int i = 0; i < n; i++) {
                        for (int j = 0; j < n; j++) {
                            int m = ((i + 1) + (j * n)) - 1;
                            System.out.print(p[m] + "\t");
                        }
                        System.out.println();
                    }
                    break;
                } else {
                    JOptionPane.showMessageDialog(null,
                    "Sorry, your input must be higher than 0!",
                    "System Error", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(null,
                "You must entering number not word!", "System Error",
                JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

代码使用了try-catch,因为这行

int n = Integer.parseInt(JOptionPane.showInputDialog("Enter your number!"));

不是因为“非递归”。要使程序递归,将逻辑放入方法而不是执行循环,再次调用方法本身。仅当条件为(非)为真时才执行调用。在这种情况下,不要再次调用该方法,而是返回计算值(或其他内容)

除此之外,还有更容易的代码来检查数字是否为素数...