Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: How do I let the user choose how big an array is...

1. ## How do I let the user choose how big an array is...

...but that user doesn't know how big the array is going to be off the top of his head.

Let's say I have a for loop that takes user input (integers) and stores them into an array. But the loop doesn't exit until a negative number is typed. How would I do that to make sure I don't go out of bounds of the array, but I don't want a ton of extra values left over either? Because I'm going to sum these numbers once it's all done, and I don't want the 0 values effecting my sum.

2. ## Re: How do I let the user choose how big an array is...

ArrayList (Java Platform SE 6) gives you a dynamic array where an initial size isn't required.

3. ## Re: How do I let the user choose how big an array is...

The underlying implementation of Arraylists (and Vectors for that matter):

Create an array of some capacity. You will need 1 other variable to hold the actual number of elements in the array. Then, all you need to do is define a few operators:

1. Add - Adds an element to the end of the array. If the size of the array is equal to the current capacity, you need to allocate a larger array (generally 1.5x or 2x as large) and copy over all the items inside your old array. Increase size by 1.
2. Set - same as assigning an element in the array a value. You will need to check to make sure the index passed is less than size otherwise you're assigning an invalid location.
3. Remove - moves all emements behind the given index up by 1. decrease the size by 1.
4. Insert - Check to see if the current size is less than the capacity. If it is, move all elements behind the given index one space back and put the item into that spot. Increase the size. If it's not, allocate a new array (in the same process as described in add). Add all items from the original array up to the index. Add the new item. Add all the items after that index. Increase the size.