我在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