doesitmatter
doesitmatter

Reputation: 17

trouble writing a method to print an array of primes

When I compile I get an error saying "cannot find symbol" pointing to my arr.add(j) line. Can someone explain what's wrong with my code?

public class MyClass {
    public static boolean IsPrime(int p) {
        for (int i = 2; i < p; i++) {
            if (p % i == 0 && i != p)
                return false;
            }
            return true;
        }
    }

    public static int[] GetPrimes(int n) {
        int[] arr = new int[n];
        for (int j = 1; j <= n; j++) {
            if (IsPrime(j) {
                arr.add(j);
            }
        }
        return arr;
    }
}

Upvotes: 0

Views: 51

Answers (2)

Bohemian
Bohemian

Reputation: 425198

Java ain't javascript: Arrays have no methods (beyond those inherited from Object, which are essentially useless).

Use a List<Integer> instead.

List<Integer> arr = new ArrayList<>();
...
arr.add(j);
...
return Arrays.asList(arr);

Upvotes: 3

Jens
Jens

Reputation: 69460

this line arr.add(j);have to be changed to arr[j]; because you have an array not a List object.

Also your class name have to start with a character.

Upvotes: 0

Related Questions