2017-06-20 44 views
0

所以我寫了這個小程序,它應該檢查一個數是否是素數,如果是這種情況,應該將其添加到數組列表中。問題是,它只是添加數字3,然後停下來。請有人解釋我爲什麼這樣做?我的程序應該計算素數,但在第一個數字後停止

import java.util.ArrayList; 
public class main{ 
    public static void main(String args[]){ 
     ArrayList Primzahlen=new ArrayList(); 
     int current=1; 
     boolean prim=true; 
     for(int a=0;a<100;a++){ 
      for(int b=2;b<current;b++){ 
       if(current%b==0){ 
        prim=false; 
       } 
       if(b==current-1){ 
        if(prim==true){ 
         Primzahlen.add(current); 
        } 
       } 
      } 
      current++; 
     } 
     System.out.println(Primzahlen); 
    } 
} 
+3

你應該嘗試通過您的代碼在調試器步進。 – hatchet

+4

如果'current%b == 0'設置'prim = false',但您從未再次將其設置爲true。 –

+0

謝謝。我認爲我不應該錯過這樣一個明顯的錯誤。 – LuisIsLuis

回答

0

您需要在檢查當前值後重置prim爲真。

public static void main(String args[]){ 
     ArrayList Primzahlen=new ArrayList(); 
     int current=1; 
     boolean prim=true; 
     Primzahlen.add(2); 
     for(int a=3;a<100;a++){ 
      for(int b=2;b<current;b++){ 
       if(current%b==0){ 
        prim=false; 
       } 
       if(b==current-1){ 
        if(prim==true){ 
         Primzahlen.add(current); 
        } 
       } 
      } 
      prim=true; 
      current++; 
     } 
     System.out.println(Primzahlen); 
    } 

通知古板=真正接近目前++

+0

或者只是將'boolean prim = true;'向下移動一行,如評論中建議的@ saka1029所示。 –

+0

解決問題的方法很多。我在看到評論之前發佈了它。 –

相關問題