-1

I am just learning java and have an issue writing a program that uses the sieve of Eratosthenes. The compilation error is below the code. Any help with this problem is greatly appreciated. Thanks much.

public class Main {

    public static void main(String[] args) {

        int[] arr = new int[1000000];
        for (int i = 0; i < 1000000; ++i) 
        {
                arr[i] = i;
        }

        sieve(arr);
        for (int elem :arr)
        {
            System.out.println(elem);
        }
    }

    public static void sieve(int[] array) 
    {

        int n = 0;

        for (int i = 2; i < 1000; ++i) 
        {
            if (arr[i] != 0) 
            {
                for (int  j = (int)Math.pow(i, 2) + n * i; j < 1000000; ++j)
                {
                    do 
                    {
                        arr[j] = 0;
                        n++;
                    }while ( n < 1000000);
                }
            }
        }
    }
}

Here is the compilation error javac project3.java

project3.java:23: error: cannot find symbol
    if (arr[i] != 0) {
        ^
  symbol:   variable arr
  location: class project3

project3.java:28: error: cannot find symbol
            arr[j] = 0;
            ^
  symbol:   variable arr
  location: class project3

2 errors

** I compiled this as class project3

Kevin
  • 551
  • 1
  • 9
  • 28
garserdt216
  • 163
  • 6

2 Answers2

1

You have two static methods, in the first you define the array arr but it is not defined in the second method. You probably meant to use array (which is the parameter of sieve) at lines 23 and 28.

bobylito
  • 3,172
  • 22
  • 27
  • Yup! Jeez... Thanks! ...but now I see I'm printing zeros past 3.... At least I see that now. – garserdt216 Jan 07 '16 at 09:04
  • @garserdt216 If his answer is what helped you, you should mark it as the accepted answer. That rewards bobylito for helping you and encourages people to answer your questions in the future. – Kevin Jan 07 '16 at 17:12
  • Thanks for the suggestion Kevin! – garserdt216 Jan 08 '16 at 00:09
0

Replace arr[i] with array[i] in sieve().

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256