Prime Directive Help

https://www.codecademy.com/courses/learn-java/projects/java-prime-directive

I have similar problem :

// Import statement:

import java.util.ArrayList;

class PrimeDirective {

  

  // Add your methods here:

  public boolean isPrime(int number){

    return number;

if (number == 2) {

return true;

}else if (number < 2) {

  return false;

}

    for (int i = 2; i < number; i++)

    if (number % i == 0) {

      return false;

    }

public ArrayList<Integer> onlyPrimes(int[] numbers) {

  ArrayList<Integer> primes = new ArrayList<Integer>();

  for (int number : numbers) {

    if (isPrime(number)) {

      primes.add(number);

    }

  }

  return primes;

}

  public static void main(String[] args) {

    PrimeDirective pd = new PrimeDirective();

    int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};

System.out.println(pd.isPrime(6));

  }  

}

Hi there, welcome to the forums.

Can you tell us what the problem is that you’re having with the project? :slight_smile:

Hi, I’m having issues with the method onlyPrimes(). The output of this method is meant to show only the prime numbers in the Array at the bottom of the code, but for some reason by my code its outputting the entire Array. Some help please!

Here is my code:
import java.util.ArrayList;

class PrimeDirective {

public boolean isPrime(int number){

if(number < 2){

  return false;

}

for(int i = 2; i < number; i++){

  if(number % i == 0){

    return false;

  }

}

return true;

}

public ArrayList onlyPrimes(int numbers){

ArrayList<Integer> primes = new ArrayList<Integer>();

for(int number : numbers){

  isPrime(number);

  primes.add(number);

}

return primes;

}

public static void main(String args) {

PrimeDirective pd = new PrimeDirective();

int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};

System.out.println(pd.onlyPrimes(numbers));

}

}

1 Like

I ran into the same problem and it took me quite a while to figure out…

The problem is with the onlyPrimes method.

You are stating that all number in numbers is prime. You need a conditional that tests if the number is prime, then the number is added to primes.

Hi!
I need some help with my code.
My error message keep saying that I am missing a return.
But clearly I don’t know what is missing. So please take a look at it and give feedbacks. Thank you!

// Import statement:
import java.util.ArrayList;
class PrimeDirective {

// Add your methods here:
public boolean isPrime(int number){
if (number == 2){
return true;
System.out.println(“It is the smallest prime number”);
} else if (number < 2){
return false;
System.out.println(“It is not a prime number”);
}
for (int i = 2; i < number; i++) {
if (number % i == 0){
return false;
} else {
return true;
}
}
}

public static void main(String args) {

PrimeDirective pd = new PrimeDirective();
int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};
System.out.println(pd.isPrime(6));

}

}