java - How to delete elements from an array? -
how delete integer @ given index , how compress myints
?
this got keep getting error.
public void deleteint(int index) { int[] newints = arrays.copyof(myints, myints.length); if (myints[index] != 0) { myints[index] = 0; (int : myints) { if (myints[i] != 0) { newints[i] = myints[i]; } } } myints = newints; currentint++; }
this error get:
exception in thread "main" java.lang.arrayindexoutofboundsexception: 11
this code doesn't use enhanced loop properly:
(int : myints) { if (myints[i] != 0) { newints[i] = myints[i]; } }
it tries read element myints, content of element, not index. so, element contains value > array's length the outofbounds exception.
public void deleteint(int index) { // can 1 element shorter going erase 1 element // also, copying contents of original array in waste of time // create it. int[] newints = new int[myints.length-1]; // easiest way use variable track insertions in // new array int j=0; (int i=0; < myints.length; i++) { if (i != index) { newints[j++] = myints[i]; } } // have new shortened copy of array, function void, // life ends here :) }
Comments
Post a Comment