java arrays error: /tmp/java_959p0x/TestPrimeDividers.java:30: error: cannot find symbol return arr;

161 Views Asked by At

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
1

There are 1 best solutions below

0
On

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.