Rods2292
Rods2292

Reputation: 675

Method to calculate prime numbers - [JAVA]

I need to build a method that calculates a prime number for my homework. I implemented the algorithm proposed by my professor but it's not working.

Eclipse gives the message: The local variable prime may not have been initialized and does not compile.

Can someone help me?

public static boolean itsPrime(int nbTest){

    boolean prime;

    if (nbTest <= 1){
         prime = false;
    } else if (nbTest == 2){       // Two is the only even number that is prime
        prime = true;
    } else if ((nbTest != 2) && (nbTest % 2 == 0)){    // If it's even and different than two it is not prime
        prime = false;
    } else {
        for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){ 
            if (nbTest % i == 0){
                prime = false;
            } else {
                prime = true;
            }
        }   
    }

    return prime;
}   

Upvotes: 1

Views: 197

Answers (2)

Sweeper
Sweeper

Reputation: 275095

You did not initialize the variable prime in your code. By just looking at it, you saw that every branch of the if statement assigns a value to prime. However, there is one exceptional case, what if the for loop doesn't get executed? Then the value of prime is unknown! So that's why the error appears.

I guess you want to return false if the loop doesn't get executed so just initialize prime with false when you declare it:

boolean prime = false;

To make your code better, instead of just assigning values to prime, you can just return! Let me show you the full code:

public static boolean itsPrime(int nbTest){

    boolean prime = false;

    if (nbTest <= 1){
         return false;
    } else if (nbTest == 2){       // Two is the only even number that is prime
        return false;
    } else if ((nbTest != 2) && (nbTest % 2 == 0)){    // If it's even and different than two it is not prime
        return false;
    } else {
        for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){ 
            if (nbTest % i == 0){
                prime = false;
            } else {
                prime = true;
            }
        }   
    }

    return prime;
}   

Upvotes: 1

Ryan Turnbull
Ryan Turnbull

Reputation: 3944

Just initialise it when you declare the variable. EG

boolean prime = false;

Upvotes: 2

Related Questions