gpt4 book ai didi

java - 如何在java中使用扫描仪时删除ArrayList中的特定对象

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:10 25 4
gpt4 key购买 nike

我正在尝试通过我的输入(扫描仪)从我的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 specifiedelement from this list, if it is present (optional operation). If thislist 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). Returnstrue if this list contained the specified element (or equivalently, ifthis 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com