java - complete a method that swaps the first and second half of an array of integers -
i keep getting out of bounds error whenever try run code. know wrong it? can't seem figure out.
public class swapper{ /** method swaps first , second half of given array. @param values array */ public void swapfirstandsecondhalf(int[] values) { // work here int[] first = new int[values.length/2]; int[] second = new int[values.length/2]; for(int = 0; < values.length / 2; i++) { second[i] = values[i]; } (int j = values.length / 2; j < values.length; j++) { first[j] = values[j]; } for(int k = 0; k < values.length / 2; k++) { values[k] = first[k]; } for(int l = values.length / 2; l < values.length; l++) { values[l] = second[l]; } } // method used check work public int[] check(int[] values) { swapfirstandsecondhalf(values); return values; } }
int[] first = new int[values.length/2];
so indexes [0..values.length/2 - 1]
valid first
.
for (int j=values.length/2; j<values.length; j++) { first[j] = values[j]; }
so first value of j
being values.length/2
, it's out of bounds.
you need practice debugging, placing break point , tracing code executes.
Comments
Post a Comment