-3

Can you please help me figure out why I am getting an error in this Java program?

public class TestPrimeDividers {
    public static boolean isPrime(long n) {
        boolean flag = true;
        for (int i = 2; i < n && flag ; i++) {
            if ((n % i) == 0)
                flag = false;
        }
        return flag;
    }
    public static long [] primeDividers(long n) {
        if (isPrime(n)) {
            long arr[] = new long [0];
            return arr;
        } else {
            int j = 0;
            for (int i = 2 ; i < n; i++)
                if (isPrime(i))
                    j++;
            long arr[] = new long [j];
            j = 0;
            for (int i = 2; i < n; i++)
                if (isPrime(i)) {
                    arr[j] = i;
                    j++;
                }

        }
        return arr;
    }
    public static void main(String[] args) {
        long arr [] = primeDividers(6);
    }
}

The error I get is:

/tmp/java_959p0x/TestPrimeDividers.java:30: error: cannot find symbol
return arr;
       ^
  symbol:   variable arr
  location: class TestPrimeDividers
1 error
vefthym
  • 7,422
  • 6
  • 32
  • 58
  • 1
    Possible duplicate of [What does a "Cannot find symbol" compilation error mean?](http://stackoverflow.com/questions/25706216/what-does-a-cannot-find-symbol-compilation-error-mean) – MC Emperor Dec 27 '16 at 20:29

1 Answers1

2

In Java, variables are scoped to the blocks in which they are declared. Your method primeDividers declares two different variables named arr, both within different nested blocks; neither is accessible at the top level. Therefore, when you try to return arr from the top level of the method, you get an error.

Try declaring your variable at the top of your function, before you enter any nested blocks.

user3553031
  • 5,990
  • 1
  • 20
  • 40