0
   public static int createArray(int theListSize)
  {
    ArrayList<Integer> possiblePrimeNum = new ArrayList<Integer>();
    
    for (int i=0; i<=theListSize; i++) //simply creates the array
    {
      possiblePrimeNum.add(i, i+2);
    }
    return possiblePrimeNum;
  } 

I don't understand this code. I mean that I understand what I'm going to do, but I don't know why the array won't return. What's wrong here?

possiblePrimeNum=createArray(theListSize);

Ludwig
  • 3
  • 1
  • `public static int ` <- The method is only declared to return a single `int`. If you want to return a `List`, then declare as doing so, `public static List ` – MadProgrammer Sep 25 '21 at 03:19
  • "I don't know why the array won't return." Well, what *does* happen? I assume what happened - based on my own knowledge of Java - is that you get an error message. Did you *read* the error message? Did you *understand* the error message? Separately: when you write `public static int createArray(int theListSize)`, what do you think the `int` right after `static` means? Do you see how that conflicts with the intent of your code? – Karl Knechtel Sep 25 '21 at 03:26

1 Answers1

0

You declared this method as returning a single int value, a single number, and a primitive (not an object).

An ArrayList is a collection of numbers, Integer objects (not primitives).

You said:

Dynamic 1D Array

I do not know what you mean by "Dynamic".

An array in Java is not the same as an ArrayList. The first is a built-in basic type in Java. The second is a class found in the Java Collections Framework, bundled with all Java distributions.

You asked:

I mean that I understand what I'm going to do, but I don't know why the array won't return.

Change your method to return a List of Integer objects rather than a single int. Something like this.

public static List < Integer > possiblePrimes ( final int countOfPrimes )
{
    List < Integer > possiblePrimes = new ArrayList < Integer >( countOfPrimes );
    for ( int i = 0 ; i <= countOfPrimes ; i++ ) 
    {
        possiblePrimes.add( i , i + 2 );
    }
    return List.copyOf( possiblePrimes );  // Return a unmodifiable list, as a general best practice.
}

Call that method like this.

List < Integer > maybePrimes = App.possiblePrimes( 7 );
System.out.println( "maybePrimes = " + maybePrimes );

When run:

maybePrimes = [2, 3, 4, 5, 6, 7, 8, 9]

I think your algorithm for finding candidate primes needs some more work. ‍

If you really want an array, see:

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154