0

Please see the code below.

The task is to make the code which replaces element inserted by the user and for replacement only for-statement can be used (this is the task requirement). The rest of the elements are to be saved. E.g. when input is "1" the following output is expected "0 2 3 4"

Please help with modification of for-statement following after line "System.out.println("The following element to de deleted "+removedElement);".

If it is possible please advise on both options when "<" and ">" symbols can be 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 i = 0; i < baseArray.length; i++){ 
        System.out.println(baseArray[i]);
    }

    System.out.println("Please indicate number of element to be deleted");

    Scanner scr = new Scanner (System.in);

    int removedElement = scr.nextInt();

    System.out.println("The following element to de deleted "+removedElement);

    for (int i = baseArray.length; i>removedElement; i--){
        **baseArray[i]=baseArray[i];**

    }

    scr.close();

    for(int i = 0; i < baseArray.length-1; i++){ 
        System.out.println(baseArray[i]);
    }

}

}
  • An array has a fixed size. You can't just "remove" an element from it – OneCricketeer Nov 05 '16 at 21:37
  • 1
    I suggest stepping away from the computer and figuring out how to do this by hand. Picture the array as a row of chairs with students sitting in them. How would you "remove" a student from the row and fill in the now empty seat while maintaining the order of the students? – Code-Apprentice Nov 05 '16 at 21:39

1 Answers1

1

It seems that by "deleting" an element, you want to overwrite the element-to-delete by shifting all elements after it one position to the left. To do that, start from the position to remove, iterate until one before the last position, and copy values from the next position:

for (int i = removedElement; i < baseArray.length - 1; i++) {
    baseArray[i] = baseArray[i + 1];
}

For the record, this operation is possible without a for loop, faster, using System.arraycopy:

System.arraycopy(baseArray, removedElement + 1, baseArray, removedElement, baseArray.length - removedElement - 1);
janos
  • 120,954
  • 29
  • 226
  • 236