开发者

How to make Java recursive with this code?

开发者 https://www.devze.com 2023-02-21 19:27 出处:网络
I have code that can make output prime number but this program using try and catch. Can you help me change this program with using recursive?

I have code that can make output prime number but this program using try and catch. Can you help me change this program with using recursive?

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);
            }
        }
    }
}


The code uses try-catch because of this line

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

not because of "non-recursiveness". To make a program recursive, put the logic into a method an instead of performing a loop, invoke the method itself again. The invocation is only performed if a condition is (not) true. In this case, do not invoke the method again but return the calculated value (or something else)

Besides this there is much easier code to check a number to be prime...

0

精彩评论

暂无评论...
验证码 换一张
取 消