[CSC 204] Example of how to resize an array

Andrew J. Pounds pounds_aj at mercer.edu
Wed Apr 8 04:49:02 EDT 2009


For those that did not come to class on the day I discussed this...

public class PrimeArray{

    public static void main(String[] args){

        final int MAX_NUMBER = 1000;

        int[] array = new int[1];

        int number = 2;
        array[0] = number;


        while ( number < MAX_NUMBER  ){
            boolean foundPrime = true;
            for (int i=0; i<array.length; i++)
                if (foundPrime &&  ((number % array[i]) == 0))
                        foundPrime = false ;


            if (foundPrime) {
                int[] newArray = new int[array.length+1];
                for (int i=0; i<array.length; i++)
                    newArray[i] = array[i];
                newArray[newArray.length-1] = number;
                array = newArray;
                newArray = null;
            }
            number++;
        }

        for (int i=0; i<array.length; i++)
            System.out.println(array[i]);
    }
}

-- 
Andrew J. Pounds, Ph.D.  (pounds at theochem.mercer.edu)
Associate Professor of Chemistry and Computer Science
Mercer University,  Macon, GA 31207   (478) 301-5627



More information about the csc204 mailing list