2011-04-02 40 views
0

我有代码可以使输出素数,但使用trycatch这个程序。你能帮我用递归来改变这个程序吗?如何使用此代码进行Java递归?

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

这是功课? – MAK 2011-04-02 08:20:08

回答

3

代码使用的try-catch,因为这条线

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

不是 “非递归” 的,因为。为了使程序递归,将逻辑放入方法而不是执行循环,再次调用方法本身。只有在条件(非)为真时才会执行调用。在这种情况下,不要再次调用该方法,但返回的计算值(或别的东西)

除此之外还有更容易代码来检查一些是素数...