I have code which allows a user to delete an element from an array that they select however I then want to move all existing elements "down one" so there are no gaps left in the array.
At the moment if I delete the first element (index 0) it is deleted but if I add information to the array it is entered at index 1 and index 0 is left null. If something is deleted from an index which has information in the following indices how can I move all the information down one index?
My delete method:
static void deleteStudent() {
System.out.println("Wish student would you like to delete?");
for(int i=0;i<9;i++) {
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
for(int i = studentChoice+1; i<studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
}
EDIT:
I added four entries to the array:
[one, two, three, four, null, null, null, null, null, null]
I ran then program and tried to delete index [2], this was successful outputting the following:
[one, two, four, null, null, null, null, null, null, null]
as you can see the the elements where moved down as wanted, the problem is then when I add a value to the array again the deleted index is passed over and the element is entered into the next index, see below:
[one, two, four, null, newadd, null, null, null, null, null]
How can I have the program entering the new value into the correct array?
Add method:
static void addStudent() {
if (nameArrayCount < 10) {
System.out.println("Enter the student's name in the following format - surname, forename: ");
studentName = input.next();
studentNamesArray[nameArrayCount] = studentName;
nameArrayCount = nameArrayCount + 1;
}
else if (nameArrayCount == 10) {
System.out.println("******Array is full, please delete a student before adding another.*****");
}
if (markArrayCount < 10){
System.out.println("Enter the first mark: ");
markOne = input.nextInt();
System.out.println("Enter the second mark: ");
markTwo = input.nextInt();
System.out.println("Enter the third mark: ");
markThree = input.nextInt();
studentMarksArray[markArrayCount][0] = markOne;
studentMarksArray[markArrayCount][1] = markTwo;
studentMarksArray[markArrayCount][2] = markThree;
markArrayCount = markArrayCount + 1;
}
}