简体   繁体   中英

My program should calculate prime numbers, but stops after the first number

So I wrote this little program that is supposed to check if a number is a prime number and if it's the case should add it to an arraylist. The problem is that it just adds the number 3 and then stops. Could somebody please explain me why it behaves like that?

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);
    }
}

You need to reset prim to true after you are over with checking the current value .

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);
    }

Notice the prim=true near current++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM