我在java中有一个数组有问题。我尝试使用线程并在数组中添加素数,但它不起作用。我希望b [c]将所有素数从firstnumber存储到secondnumber。素数数组不能正确打印内容
public class btl {
public static boolean IsPrime(int n) {
if (n < 2) {
return false;
}
int squareRoot = (int) Math.sqrt(n);
for (int i = 2; i <= squareRoot; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanIn = new Scanner(System.in);
int first = 0;
int second = 0;
try {
System.out.println("Input First Number");
first = scanIn.nextInt();
System.out.println("Input Second Number");
second= scanIn.nextInt();
}
catch(Exception e) {
System.out.println("Something wrong!");
}
int x = first;
int y = second;
int a;
int[] b = new int[y];
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
int c=0;
for(int i=x; i<y; i++)
{
if(IsPrime(i)) {
b[c] = i;
c++;
System.out.println(b[c]);
}
}
}
});
threadA.start();
}
请不要张贴文字的截图。把文字放在你的问题中。 – khelwood
说“但它不是工作”是不够的。说出它的作用,以及它与你期望/想要的不同。 –
您在增加'c'后立即打印'b [c]'。所以你总是打印零。您正在将*元素*打印到刚分配的元素上。 – khelwood