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

标签 java object arraylist java.util.scanner

我正在尝试通过我的输入(扫描仪)从我的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/

相关文章:

javascript - 返回一个对象 - javaScript

java - java中修改列表会影响另一个列表

java - JavaFX-插入从音频文件获取的媒体标签后,ArrayLists打印为空

java - 创建包含多个同名文件的 zip

Java JSON写入jsonarray循环

Java监控activemq但不轮询队列

python - 您可以在类和类的实例上调用方法吗?

java - 动态比较字符串和对象的 toString() 方法

java - 如何在 Java 中存储、排序和打印字符串和 double 的 2D "array"?

java - 带有奇怪 NullPointerException 的建议