Prime Directive help

Hi Everyone, i need help.with my code.

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

}

}

I keep getting a “missing return statement” error message whenever i compile my code, is anyone able to help?

Hello spitfirez, welcome to the community.:+1: :+1: :+1:

The first problem I see with your code is that it is not formated, which makes it hard for me to read. You can format your code by using this button: </>

Next, with your code. Inside your for-loop, you don’t want that else return true part… because it means that if the number is not dividable by two,(e.g. 9) it returns false. Then if it is divided by three, it will return true. This means that you will have multiple return statements from one input, which doesn’t work.

Also, you don’t want the condition to be:

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

but rather

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

This because the definition of prime is a number that cannot be divided evenly by anything other than 1 and itself. If you use <= then it will be able to divide evenly so that it will return false.

Hope this helps!!:smiley:

1 Like