Hello , This is delete function . Now I don\'t understand 3 points ( I circled t
ID: 3654821 • 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
1. The -1 is because the length of the list has shrunk by one. You have deleted a person.
2. This moves the next entry in the list back one position and list and overwrites what is currently there. You have deleted a the name of a person. We then have to move all the names that occur after this person's name back 1 in the list in order to fill the gap left.
3. Because you have deleted a person, the -- decrements the nPerson variable by 1. In other words, the number of persons is now 1 less than it used to be.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.