0
我有代碼可以使輸出素數,但使用try
和catch
這個程序。你能幫我用遞歸來改變這個程序嗎?如何使用此代碼進行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);
}
}
}
}
這是功課? – MAK 2011-04-02 08:20:08