java - ArrayExceptionOutOfBounds when returning the method -
i attempting create fillarray method fills , array 20 random values , sums every third value. getting arrayexceptionoutofbounds @ line 21 when method called. through debug have watched array fill proper values , sum calculated. wondering error is.
public static void fillarray(){ //adding a[0], a[3], a[6}, ... double[] = new double[20]; for(int = 0; < a.length; i++) a[i] = math.random(); double sum = 0; int k = 0; do{ k += 3; sum += a[k]; }while(k < 20); system.out.println("sum = " + sum); }
again looking determine reason error not way fix it.
here problem:
do{ k += 3; sum += a[k]; }while(k < 20);
k equal 0, 3, 6, etc, until reaches 21 , try , access a[21] out of bounds.
this because when k = 18 on 6th iteration of while loop, (k < 20)
true , therefore while loop continues , adds 3 k making 21. after that, while loop stops k not less 20 anymore leaving k value of 21.
Comments
Post a Comment