You can simply change all your for loops to the form for (int i = 0; i < count; i++)
- this way the loops will only loop the numbers that were actually set, not all numbers in the array.
BTW: If you ever need some variable-sized array in the future you can use a List
(from the java.util
package). In your example I would use an ArrayList<Integer>
. This is a list that uses an array internally, but increases its size if the array gets too small (by creating a new array and copying the contents).