Hey, just a quick question, I have a function to double the size of a string array and another function to use StdIn to populate the array

my code is

    public static String[] read() {
        String[] a = new String[5]; 
                for (int i = 0; i < a.length; i++)
                a[i] = StdIn.readString();
                if (a[a.length-1] != null) { double(a); } 
                    for (int i = 0; i < a.length; i++) 
                System.out.print(a[i]); System.out.println(); 
            return a;

I know the bit (a[a.length-1] != null).... etc is wrong but don't know how to fix it. What I want it to do is, set up an initial array, populate it with StdIn read, but if the inputs are more than the array size (5) then use my double function to copy the array and expand it to twice the size, and keep doing this as neccesary.

Thank you for any help!

4 Years
Discussion Span
Last Post by JamesCherrill

Your double(a) method isn't going to work without a return value. All java method parameters are passed by value - the parameter in the method is a copy of the original value. The "a" that you are manipulating in your method is just a copy of the "a" reference that was passed to you, so whatever you do in the method doesn't chnage the "a" reference in the calling method. You presumably create new array of twice the size in the double method, but that will be garbage collected when the double method terminates because there are no references to it outside the method.
To make this work you need to explicitly return the new array, and assign the reference in your calling method to that array, ie

public String[] double(String[] in) {
   return (a new array twice the size of in);

a = double(a);

Thank you, I understand that now! One more question, my method double, doubles the array and copies the values of the original array over. With my array length of 5, if I entered e t u i o p u how would I get it top copy the first 5 over and then carry on and put the rest of the string in too?


You more-or-less have that now..

arrayIndex = 0
loop while file has more values
   read next value from file
   if arrayIndex >= array size
       create new larger array and copy existing entries into it
   insert value in array
This article has been dead for over six months. Start a new discussion instead.
Please be thoughtful and detailed and be sure to adhere to our posting rules.