【发布时间】:2017-05-26 05:38:05
【问题描述】:
我正在尝试使用对象的名称在另一个类中的数组列表中查找一个对象。
private void listParticipant() {
System.out.print("Put in name of participant to see if currently registered: ");
String name = readString();
for (Team team : teamList) {
if (team.hasParticipantWithName(name)) {
System.out.println("Participant is registered.");
return;
}
}
System.out.println("Participant does not exist.");
}
但即使我知道列表包含我输入的名称,它也会返回“参与者不存在”。
这是我用来查找名称的团队类中的方法:
public boolean hasParticipantWithName(String name) {
for (Participant part : participantList) {
if (name.equals(part.getFullName())) {
return true;
}
}
return false;
}
这是我在另一个类中的getFullName 方法,其中包含参与者的构造函数。
public String getFullName(){
String capitalizedLastName = lastName.substring(0, 1).toUpperCase()+lastName.substring(1);
String capitalizedFirstName = firstName.substring(0, 1).toUpperCase()+firstName.substring(1);
return (capitalizedFirstName + " " + capitalizedLastName);
}
使用构造函数添加对象
public Participant(String firstName, String lastName, int id)
然后输入例如“john smith”和“John Smith”
我的读取字符串是
private String readString() {
return keyboard.nextLine().toLowerCase();
}
我不知道如何解决它。我试过用小写和大写的第一个字符来调用名称,但该方法在所有内容上都返回“不存在”。有任何想法吗? :)
【问题讨论】:
-
仅凭给定的代码很难说出来(尽管我猜
Object#equals没有被覆盖)。您可能希望包含一个 MCVE,以便我们能够重现该行为并能够做出回应。 -
请给一个输入示例..
-
你能提供一个搜索名字的例子吗?还有
readString方法 -
显然需要minimal reproducible example 或至少需要名称和团队值
-
我会鼓励你学会自己调试。如果 A 不等于 B 但您确信它们相等,那么为什么不在比较之前打印出 A 和 B 的值呢?也许他们不是你期望的那样?
标签: java arrays list class object