简体   繁体   中英

I can't find the bug in my java method that returns an array of prime numbers.

It only uses the prime numbers to check if the other numbers are also prime

static public int[] primeGen(int a){

    int[] series={2};

    if (a==1 || a==2 || a<=0){
        return series;
    }   

this is where the errors occur

    else{

        boolean Prime = false;

        for (int i = 3; i<=a; i++){

            boolean[] state = {};

            for (int j = 0; !(state[state.length-1]) && (j<series.length); j++){
                state = Arrays.copyOf(state, state.length +1);
                state[state.length -1] = i % series[j] ==0;
            }

            for (int k = 0; (Prime) && (k<state.length); k++){
                Prime = !(state[k]);
            }

            if (Prime){
                series = Arrays.copyOf(series, series.length +1);
                series[series.length -1] = i;
            }
        }
        return series;
    }
} 

Sorry if I just made a rookie mistake, cause I've been learning Java for 3 days now

您的state数组被初始化为空数组,所以!(state[state.length-1])试图访问该数组的无效索引(-1)。

This line

for (int k = 0; (Prime) && (k<state.length); k++){

means that the loop will only be executed if Prime is true. However you have initialized Prime to false and only set it true inside the loop.

It looks like you are using Arrays.copyOf to increase the size of your output array. You can just use Vector.add() instead and the JVM will take care of any resizing needed.

Now it's working fine!

My mistake was that I didn't know that the for loop doesn't start at all if the statement in the middle for(int j =0; (Prime)&&(j<) ; j++){} is't true. What I thought was that this would be checked only at the end of each repetition. Anyway, I wouldn't have realized this without u guys pointing out that the statements don't add up, so thanks a lot!

        boolean Prime = false;

        for (int i = 3; i<=a; i++){

            boolean[] state = {};

            for (int j = 0; (j<series.length); j++){
                state = Arrays.copyOf(state, state.length +1);
                state[state.length -1] = i % series[j] == 0;
       //This is where I added my statement that breaks the loop
                if (!(state[state.length-1]==false&&j<series.length)){break;}
            }

            for (int k = 0; (k<state.length); k++){
                Prime = !(state[k]);
       //As well as here
                if (!(Prime==true&&k<state.length)){break;}
            }

            if (Prime == true){
                series = Arrays.copyOf(series, series.length +1);
                series[series.length -1] = i;
            }
        }
        return series;
    }
} 

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