I am trying to figure out how to increase array size... let say i created string array that can hold 7 names but the user wanted to enter more than 7... so i am trying to write a program that double my array size with out me changing it manualy ....

this is what i have so far...but it is not doubling my arry ...

public static void main(String[] args) throws IOException  
    {
        System.out.println("please enter names");
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

        String array[] = new String[7];
        int count = 0;
        for (int index = 0; index < array.length; index++ )
        {
            if( count == array.length)
            {
                String [] temp = new String[array.length * 2];
                for ( int i = 0; i < array.length; i++)
                {
                    temp[i] = array[i];
                    array = temp;

                }
            }
            array[count] = read.readLine();
            count++;

           array[index] = read.readLine();
           System.out.println("array["+index+"] = "+array[index]);
        }
        System.out.println( Arrays.toString(array) );

     }

}

Can you post what the program prints out that shows the problem?

What code should be executed every time the copy loop goes around and what code should only be executed one time after the copy loop completes?

If you are confused about what goes where, post a list of the steps the code should do in pseudo code so we can see what the logic is you are trying to program and work on it to get it right.

Edited 4 Years Ago by NormR1

please enter names
john
array[0] = john
mike
array[1] = mike
linda
array[2] = linda
right
array[3] = right
wrong
array[4] = wrong
true
array[5] = true
false
array[6] = false
[john, mike, linda, right, wrong, true, false]

That is the output...I dont want the program to stop taking input...i want to let the program accept input more than six array space..i want the program be self-maintaining.
That is, the array should never get full. When you fill up the array, you should expand it
to accommodate new words.... my program stops when it gets array[6]....

What do you mean by "program stops"? Is there a message?

Try debugging the code by adding some printlns. For example print out the value of count just before the if statement that compares count's value. The print out should help you see what the code is seeing and understand why the code is executing the way it is.

Edited 4 Years Ago by NormR1

Just a few observations:
1) index and count appear to generally have the same value. Is there a need to have two variables?
2) Change the condition from < to <= so that the loop can continue after the existing limts of the array.
3) I do not see how you intend to exit the program. How should the user indicate that there is no more input and to exit the loop? A blank line perhaps?

in order to 'change the size of an array', you need to create a new array entirely.

something like this:

String[] myArray = new Array[7];
static int count = 0;

...

public void addElement(String el){
  if (count == myArray.length){
    String[] tempArray = new String[count+1]; // to reduce overhead, 
    // increase from 1 to ...
    for ( int i = 0; i < count; i++){
      tempArray[i] = myArray[i];
    }
    myArray = tempArray;
    tempArray = null; // don't need this anymore, set ready for the GC
  }
  myArray[count] = el;
  count += 1;
}

but an array itself has a fixed size, zo just "adding" an eight element to an array which only has room for 7, will lead to an ArrayIndexOutOfBoundsException.

Edited 4 Years Ago by stultuske

I would make the function more self-contained and not rely on global variables as much.

public String[] addElement(String sInsert, String[] sArray, int nPos)
// Now returning the string with the inserted element.  This way we can give the resized array instead if needed.
{
    if (nPos >= sArray.length)  // Check if we want to add the string anywhere beyond the end of the array.
    {
        String[] tempArray = new String[count + 9]; // to reduce the number of times we have to resize the array

        // Copy all the elements from the old array into the new one.
        for ( int i = 0; i < sArray.length; i++)
        {
            tempArray[i] = sArray[i];
        }
        sArray = tempArray;   // Replace the passed array with the new "resized" one.
        // The tempArray will be forgotten when it goes out of scope anyway.  Assigning to null is not needed.
    }
    sArray[nPos] = sInsert;
    return sArray;  // Make sure the possibly updated array gets back to who called it.
}

Sorry about the word-wrapped comments, but I thought I would explain my thinking and that can get a little long at times.

Edited 4 Years Ago by Nutster: Clarify. Remove unneeded step

will that change anything if you want/need to add a value afterwards?

better solution: don't, use an ArrayList

I just noticed a mistake in my code. count in line 6 should be sArray.length. This kind of behaviour is used so often that Java provides a libary class for it, called ArrayList. Use that instead for a more efficient implementation.

ArrayList is just one of many Maps, Lists, Collections ... all with their own advantages/disadvantages (depending on what it is you need)

If this is a student assignment for the purpose of learning about arrays, changing it to use a class might not teach the student about using arrays.

The problem is from your Line 6. You hard-coded the size of the array, and then use the value as the max limit of the for-loop. I guess that the compiler optimization of Java code changed the code to be a constant instead of keep checking for the array size. What you may do is to change the for-loop to a while loop instead, and also change the condition to something else besides checking for the array size (i.e. asking for continue or such).

String array[] = new String[7];
...
for (int index = 0; index < array.length; index++ ) {  // <-- problem here

// change it to...
while (GIVE_A_CONDITION) {  // change the condition to something else here
  ...
}
This article has been dead for over six months. Start a new discussion instead.