I want to deleted an element from my Student array object. The code I have only
ID: 3936480 • Letter: I
Question
I want to deleted an element from my Student array object. The code I have only deletes the first element. How can I fix it so that when it find the last name to be deleted it shifts the remaining elements to the left? Here is my code so far:
public static void enterStudentToDelete () System.out.println ("Which student would you like to delete?") Scanner scan = new Scanner (System.in); String name = scan.next(); deletestudent (students, name); public static void deleteStudent (Studentl] arr, String name) nt (Student [ arr, S for (int i = 0 ; iExplanation / Answer
Change your else if as below.
else if(arr[i].getLastName.equalsIgnoreCase(name))
{
for(int j=i;j<arr.length-1;j++)
{
arr[j] = arr [j+1];
}
arr[arr.length-1]=null;
}
explanation:
The loop
for(int j=0;j<arr.length-1;j++)
{
arr[j] = arr [j+1];
}
arr[arr.length-1]=null;
always starts at 0th position because j=0, beacause of which the below statement from loop
arr[j] = arr [j+1];
will be like arr[0] = arr [0+1];
So whenever condition from else if statement satisfies the first element(i.e arr[0]) will always replace with second element(i.e. arr[1]).
To overcome this problem you have to start inner loop from the current i th position(i.e j=i) which will replace the value at i position with the next value(i.e. i+1) in the array.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.