user2913669
user2913669

Reputation: 63

Simple Java Method Error when Returning

I'm learning methods and was trying to write code that basically tells if a number is prime. However, I keep encountering the error:

error: cannot find symbol
                return(isPrime);
                       ^
error: illegal start of type
                return(isPrime);

This is my current code (i hope i'm using the method correctly):

import java.util.Scanner;

public class DoublePalindromicPrimes{
    public static void main(String args[]){

        Scanner in= new Scanner(System.in);
        System.out.println("Please enter a number:");
        int n = in.nextInt();

        //prime(n);
        boolean resultPrime = prime(n);
        if (resultPrime){
            System.out.println("This is a prime");
        }
        else {
            System.out.println("This is not a prime");
        }
    }

    public static boolean prime(int x){
        for (int i=2;i<x;i++){
        boolean isPrime;
            if (x%i==0){
                isPrime=false;
            }
            else{
                isPrime=true;
            }
        }
        return isPrime;
    }
}

Any help is appreciated!

Upvotes: 0

Views: 104

Answers (4)

Lajos Arpad
Lajos Arpad

Reputation: 76424

public static boolean prime(int x) //throws InvalidNumberException
{
    if (x <= 0)
    {
        //throw new InvalidNumberException("The number is invalid");
    }
    int squareRoot = (int)(Math.sqrt(x));
    for (int i = 2; i <= squareRoot; i++)
    {
        if (x % i == 0)
        {
            return false;
        }
    }
    return true;
}

This is an optimized prime validator.

Upvotes: 2

nhgrif
nhgrif

Reputation: 62052

public static boolean isPrime(int x)
{   
    if(x > 2) {
        if(x%2 == 0) {
            return false;
        } else {
            int sqrt = (int)(Math.sqrt(x));
            for(int i=3;i<=sqrt;i+=2) {
                if(x%i == 0) {
                     return false;
                }
            }
        }
        return true;
    } else if(x==2) {
        return true;
    } else { //1, 0, and negatives
        return false;
    }
}

Upvotes: 4

You declared isPrime inside your loop, so the return statement can't see it. Move it outside the loop.

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240860

change it to

return isPrime;

note the space and make declaration out of isPrime for loop

Upvotes: 3

Related Questions