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)
ArrayList. It is simple to use and can resize dynamically.