我需要帮助创建一个方法来查找数组中的对象并创建一个循环来更改对象。
public void changeABFF() {
System.out.println("Enter first and the last name of the best friend you would like to change: ");
String fname = keyboard.next();
String lname = keyboard.next();
BestFriends other = new BestFriends(fname,lname,"","");
boolean found = false;
for(int i=0;i<myBFFArray.length && found == false;i++) {
if(other.equals(myBFFs.get(i))) {
found = true;
System.out.println("Enter a First Name: ");
String fName = keyboard.next();
System.out.println("Enter a Last Name: ");
String lName = keyboard.next();
System.out.println("Enter a Nick Name: ");
String nName = keyboard.next();
System.out.println("Enter a phone number");
String cPhone = keyboard.next();
BestFriends tmp = myBFFs.get(i);
tmp.firstName = fName;
tmp.setLastname(lName);
tmp.setNickName(nName);
tmp.setCellPhone(cPhone);
}
}
}
所以我从数组列表更改为数组并将名称更改为myBFFArray
我的问题是,如何创建一个find方法来匹配数组中用户输入的值?
答案 0 :(得分:0)
您可以编辑BestFriends类以覆盖equals和hashCode以比较两个BestFriends对象
public class BestFriends {
private String firstName;
private String lastName;
private String nickName;
private String cellPhone;
public BestFriends(String firstName, String lastName, String nickName, String cellPhone) {
this.firstName = firstName;
this.lastName = lastName;
this.nickName = nickName;
this.cellPhone = cellPhone;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
@Override
public int hashCode() {
return this.hashCode();
}
@Override
public boolean equals(Object obj) {
BestFriends bf = (BestFriends) obj;
return bf.getFirstName().equals(firstName) && bf.getLastName().equals(lastName) && bf.getNickName().equals(nickName) && bf.getCellPhone().equals(cellPhone);
}
之后迭代数组
public BestFriends find(String firstName, String lastName, String nickName, String cellPhone) {
BestFriends bestFriends = new BestFriends(firstName, lastName, nickName, cellPhone);
for (BestFriends b: myBFFArray) {
if (b.equals(bestFriends)) {
return b;
}
}
}