I want to deleted an element from my Student array object Th

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 ; i

Solution

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.

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 t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site