我试图编写一个程序,显示所有素数低于用户输入的素数。唯一的要求是它必须是多线程的。这是我第一次使用Java和多线程。你能帮我吗?它编译,但输出很奇怪。也许它是一个地址?
import java.util.Scanner;
import java.util.Arrays;
public class prime {
public static void main(String[] args){
// get number from user
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
RunPrime runprime1 = new RunPrime (num);
runprime1.start();
Thread.yield();
runprime1.SmallerPrimeNumbers();
}
}
class RunPrime extends Thread {
private int given_number;
RunPrime (int n) {
given_number = n;
}
public void SmallerPrimeNumbers() {
int count = 0;
for (int i = 0; i <= given_number; i++) {
if (CheckPrime(i)) {
count++;
}
}
for (int i = 0; i < count; i++) {
for (int j = 2; j <= given_number; j++) {
if (CheckPrime(j)) {
number[i] = j;
}
}
}
System.out.println(number);
}
public static boolean CheckPrime (int n) {
for (int i=2 ; i<n ; i++) {
if (n%i == 0)
return false;
}
return true;
}
}
答案 0 :(得分:0)
您的SmallerPrimeNumbers()
函数有第二个for循环,看起来不太必要。您还要分配和打印未在任何地方声明的变量number
(这可能是导致您麻烦的原因)。由于您只打印它们而不保存它们,因此您可以简化这样的功能:
public void SmallerPrimeNumbers() {
int count = 0;
for (int i = 0; i <= given_number; i++) {
if (CheckPrime(i)) {
System.out.println(i);
}
}
}