我是新来的Java
,我一直在努力地解决这个问题。无论如何,下面是一个创建Person的类,而下面是创建Phonebook
使用ArrayList
Person类型的a的类。我想编写remove函数(以便Person
从列表中删除a ),但是我的问题是,由于我仅获得人的名字,因此我无法使用Indexof函数(因为它需要对象)到达什么位置在于名字。
这是我第一次使用ArrayList
来存储对象,因此我什至不知道结果如何显示。我猜想,如果名称的位置(在我的列表中)为10,则电话为11,地址为12。我对么?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
编辑:我打算在另一个功能中使用扫描仪。不用担心
我不确定是否要获取该数组的对象,但是每个对象都已索引到该数组(具有完整属性),现在您可以使用以下代码将其删除,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
只需将arrayList和该人的名字传递给此方法
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句