2017-09-24 58 views
0

我在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(); 
} 

enter image description here

+0

請不要張貼文字的截圖。把文字放在你的問題中。 – khelwood

+2

說「但它不是工作」是不夠的。說出它的作用,以及它與你期望/想要的不同。 –

+0

您在增加'c'後立即打印'b [c]'。所以你總是打印零。您正在將*元素*打印到剛分配的元素上。 – khelwood

回答

0

你的主要問題是,你追加C首先,後來纔打印出B [C],這仍然是陣列中的空白單元格。嘗試:

for(int i=x; i<y; i++) { 
     if(IsPrime(i)) { 
      b[c] = i; 
      System.out.println(b[c]); 
      c++; 
     } 
} 

順便說一句,當你定義數組b - 你不需要所有的y單元格。申報的成本更低一些:

int[] b = new int[y-x]; 

取而代之。

+0

謝謝你的主意:D。它的工作 –

+0

輝煌@NgoHoang。您可以點擊我答案旁邊的灰色複選標記,使它變綠嗎? – Assafs

+0

我已經檢查過它。對不起,我剛開始參與計算器,所以我不知道。原諒我 –

0

在你的ThreadA運行功能,您可以通過加1 c的值,然後問打印B [C],它是那麼接下來的情況下(不填還)。所以你應該在C++行之前打印b [c]。