2017-09-24 59 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]。