0

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

1 Answer 1

3

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.