Prime Directive

Hi, can someone explain to my, what I am doing wrong?

// Import statement:
import java.util.ArrayList;
class PrimeDirective {
  
  // Add your methods here:
  public boolean isPrime (int 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;
      } 
        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(7));
    
  }  

}

the loop doesn’t seem to be part of the isPrime method.

once you fixed that, maybe to use .println to see how many iterations your loop makes?

Seems currently you only make one iteration of the loop, either true or false is returned in the first iteration of the loop, causing the method to end

Thanks, but now I have another problem, that I can’t fix, can you comment about this code too?

// Import statement:
import java.util.Arrays;
class PrimeDirective {
  
  // Add your methods here:
  public boolean isPrime (int 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;
      }
    }
    return true;
  }
  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(0));
    System.out.println(pd.onlyPrimes(numbers));
  }  
}

okay, so i found the project (for myself for quick access):

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

but trying to run your code, i don’t get any output, what do you get?


I am getting this.

seems you didn’t import ArrayList?

Oh, yes, my bad, but when I imported it there is another problem.Untitled2

method names are case sensitive. You really need to go over these thinking steps: What could cause this error? Is the method declared? Could it be a typo? Do i call the method correctly?

This is just for this problem, but all these problems you give me need these thinking steps, its crucial you teach them to yourself.

Thanks, looks like today isn’t my day.
It was so easy to fix it all, my bad.

We all have bad days, then these thinking steps to to prevent or fix mistakes are even more crucial.

kind of reminds me of this joke:

https://www.buzzmaven.com/old-engineer-hammer-2/

1 Like