I have an integer array of size 50.
So, as you know, initially the element values of this array will be all 0’s.
What I need to do is:
If the array = [12,10,0,0,……0], the for loop needs to consider only the non-zero elements, so the loop should get executed only twice..once for 12 and next for 10.
Similarly, if the array is = [0,0,0,……0], then for loop should not executed at all since all elements are zero.
If the array is [12,10,5,0,17,8,0,0,…….,0] then the for loop should get executed for the first 6 elements, even though one of the inner elements is zero.
Here is what I have.This gives me an IndexOutOfBoundsException.Please help.
Also, is there any way I can dynamically increase the size of an int array rather than setting the size to 50,and then use it in the loop? Thx in advacance for any help!
int[] myArray = new int[50];
int cntr = 0;
int x = getXvalue();
int y = getYvalue();
if (x>y){
myArray[cntr] = x;
cntr++;
}
for (int p=0; p<= myArray.length && myArray[p]!=0 ; p++){
//execute other methods..
}
//SOLUTION:
I’ve made use of an ArrayList instead of an int array to dynamically increase size of the array.
ArrayList<Integer> myArray = new ArrayList<Integer>();
To set the value of the elements-
myArray.add(cntr, x); // add(index location, value)
A cleaner way is:
The most convenient way to solve such things like this is using the appropriate Collection. For this example you might consider using an
ArrayList<Integer>.The advantage is that you do not have to preinitialize the list with a given size. It will also resize if necessary.
Another advantage is that you do not have to care about padding empty elements as well as handling empty elements at the end of the list.
The concrete problem is:
This should be illegal:
it needs to be
myArray.lengthalso you iterate from
0..50with<=this adresses51elements you do only have50elements so the correct line of code would be