Delete element from array java using for-statement -
this question has answer here:
- how remove objects array in java? 18 answers
please see code below.
the task make code replaces element inserted user , replacement for-statement can used (this task requirement). rest of elements saved. e.g. when input "1" following output expected "0 2 3 4"
please modification of for-statement following after line "system.out.println("the following element de deleted "+removedelement);".
if possible please advise on both options when "<" , ">" symbols can used.
import java.util.scanner; public class mainclass { public static void main(string[] args) { int basearray [] = {0, 1, 2, 3, 4}; system.out.println("existing array:"); for(int = 0; < basearray.length; i++){ system.out.println(basearray[i]); } system.out.println("please indicate number of element deleted"); scanner scr = new scanner (system.in); int removedelement = scr.nextint(); system.out.println("the following element de deleted "+removedelement); (int = basearray.length; i>removedelement; i--){ **basearray[i]=basearray[i];** } scr.close(); for(int = 0; < basearray.length-1; i++){ system.out.println(basearray[i]); } } }
it seems "deleting" element, want overwrite element-to-delete shifting elements after 1 position left. that, start position remove, iterate until 1 before last position, , copy values next position:
for (int = removedelement; < basearray.length - 1; i++) { basearray[i] = basearray[i + 1]; }
for record, operation possible without loop, faster, using system.arraycopy
:
system.arraycopy(basearray, removedelement + 1, basearray, removedelement, basearray.length - removedelement - 1);
Comments
Post a Comment