我正在尝试通过我的输入(扫描仪)从我的ArrayList(memberList)中删除MemberPlayer(对象)
我尝试在 google 和 Stack 上查找,但似乎找不到任何使用扫描仪的东西。
public void removeMember(){
System.out.println("Which MemberPlayer are you looking for?:");
System.out.print("Input first name: ");
String fName = input.nextLine().toUpperCase();
System.out.print("Input last name: ");
String lName = input.nextLine().toUpperCase();
for (MemberPlayer m: memberlist){
if(m.getFirstName().contains(fName) && m.getLastName().contains(lName)) {
System.out.println();
System.out.println("This MemberPlayer exist:");
System.out.println(fName + " " + lName);
System.out.print("Do you want to remove this MemberPlayer? [yes/no]");
input.nextLine().toUpperCase();
if (input.equals("Yes")) {
memberlist.remove(); //I can't figure out how to write this line?
}else{
break;
}
}else {
System.out.println();
System.out.println("This MemberPlayer doesn't exist");
System.out.println();
break;
}
}
}
我从 file.txt 中读取了我的成员列表,其中包含以下信息:名字、姓氏、年龄和团队。
ANDERS
ANDERSEN 23 1
BERT BERSEN 16 2
HANS HANSEN 25 1
TIM TIMSEN 20 2
MORTEN MORTENSEN 34 1
最佳答案
您需要使用List#remove() ,来自文档:
<小时/>boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
此外,这里不需要 for 循环
。您的方法可以简化为更加面向对象的方法:
public void removeMember() {
System.out.println("Which MemberPlayer are you looking for?:");
System.out.print("Input first name: ");
String fName = input.nextLine().toUpperCase();
System.out.print("Input last name: ");
String lName = input.nextLine().toUpperCase();
// create an object with input received
MemberPlayer m = new MemberPlayer(fName, lName);
// use contains of List
if (memberlist.contains(m)) {
memberlist.remove(m);
} else {
System.out.println("This MemberPlayer doesn't exist");
}
}
确保您覆盖 MemberPlayer
中的 .equals()
和 .hashcode()
方法。
关于java - 如何在java中使用扫描仪时删除ArrayList中的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734065/