Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello , This is delete function . Now I don\'t understand 3 points ( I circled t

ID: 3654798 • Letter: H

Question

Hello ,

This is delete function .

Now I don't understand 3 points ( I circled them )

1- Why -1 ? , why not without it ?

2- this.a[i] = this.a[i+1]; >> what this do exactly ?

3-this.nPerson--; >> What it did



The Full Code :



package ds_lab_1;



public class persons {

private String[] a;

private int nPerson;

public persons(int max)

{

this.a = new String[max];

this.nPerson =0; // array is empty

}

/// set by index

public void setPerson(int index , String name)

{

this.a[index] = name;

this.nPerson++;

}

///get persone name

public String getPerson(int index)

{

return this.a[index];

}

///find name

public int indexOf(String name)

{

int index = 0 ;

for(int i=0;i<this.nPerson;i++)

{

if(name ==this.a[i])

{

index =i;

}

}

return index;

}

//

public boolean findPerson(String name)

{

int i ;

for(i=0;i<this.nPerson;i++)

{

if(this.a[i]== name)

{

break;

}

}

if(i==this.nPerson)

return false;

else return true;

}

////////

public boolean deletePerson(String name)

{

if(this.findPerson(name))

{

int p = this.indexOf(name);

int i;

for(i=p;i<this.nPerson-1;i++)

{

this.a[i] = this.a[i+1];

}

this.nPerson--;

return true;

}

else return false;

}

///display

public String[] displayPerson()

{

String[] temp = new String[this.nPerson] ;

for(int i = 0; i<this.nPerson;i++)

{

temp[i]=this.a[i];

}

return temp;

}

}



Explanation / Answer

Well you are actually trying to delete a person from the array of persons So using the String name, you find the person by using findPerson if his name exists in the list, you try to delete the name You find out the index in the array where the name is stored, say you want to delete 'Dave' and we have a[5] = 'Dave' and we have 10 persons in total (i.e, nPerson = 10) . So we find out that the index is 5 So once we delete 'Dave', we need to update the array accordingly For that we run a for loop from index of 'Dave' (i.e 5) to 9(nPerson - 1). This is because in an array, the indexing starts from 0 So a[5] = 'Dave ' means that 'Dave' is the 6th person in the list in the for loop, we just replace every other element in the array by its next element. (i.e a[i] = a[i+1], effectively deleting 'Dave' and moving the rest of the list forward) Since we have deleted a person, the total no of persons decrease by 1 and hence we perform nPerson-- ( i.e , nPerson = nPerson - 1)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote