从 Arraylist 中删除对象如果它等于用户输入,否则只打印一次

Remove object from Arraylist If it equals userinput and else print out something only once

我现在已经尝试了大多数方法,但似乎没有用。如果用户输入特定名称,我想从 Arraylist 中删除特定对象。如果不是,我希望程序打印 "Can't find dog"。我在我的另一个 class 中有一个 getName 和 toString 方法,它与我在这个程序中的所有其他选项一起工作得很好,这是唯一不起作用的方法。

情况 4 是应该进行删除的地方。但我也希望你看看案例 3 来比较案例 3 打印出 "can't find dog" 无论如何,案例 4 打印出 "Cant find dog" 与对象一样多。

这里是主要方法:

ArrayList<Dog> doglist = new ArrayList<Dog>();
Scanner myscan = new Scanner(System.in);
boolean running = true;

while (running) {
    System.out.println("\n************************************");
    System.out.println("\nVälkommen till Kennelklubben!");
    System.out.println("\n************************************");
    System.out.println("\n[1] Register new dog");
    System.out.println("[2] Print out list");
    System.out.println("[3] Increase age");
    System.out.println("[4] Remove dog");
    System.out.println("[5] Quit program");
    System.out.println("\n************************************");
    System.out.println("\nChoose: ");

    int option = myscan.nextInt();

    switch (option) {
        case 1:
            System.out.println("Write name:");
            String name = myscan.next();
            System.out.println("Write race:");
            String race = myscan.next();
            System.out.println("Age:");
            int age = myscan.nextInt();
            System.out.println("Weight:");
            double weight = myscan.nextDouble();

            Dog dog = new Dog(name, race, age, weight);

            doglist.add(dog);

            break;
        case 2:
            System.out.println("Minimum length of tail:");
            double userInput1 = myscan.nextDouble();

            for (Dog d : doglist) {
                if (d.getTailLength() >= userInput1) {
                    System.out.println(d.toString());
                } else {
                    System.out.println("Can't find dog");
                }
            }
            break;
        case 3:
            System.out.println("Name of dog:");
            String userInput2 = myscan.next();

            for (Dog d : doglist) {
                if (d.getName().equals(userInput2)) {
                    d.increaseAge();
                    break;
                }
            }
            System.out.println("Can't find dog");
            break;
        case 4:
            System.out.println("Name of dog:");
            String userInput3 = myscan.next();
            for (Dog d : doglist) {
                if (d.getName().equals(userInput3)) {
                    doglist.remove(d.toString());
                } else {
                    System.out.println("Can't find dog");
                }
            }
            break;
        case 5:
            running = false;//Avslutar loopen och därmed programmet
            System.out.println("Programmet avslutat");
            break;
        default:
            System.out.println("Nu blev det fel, välj mellan [1] [2] [3] [4] [5]");//Felmeddelande om valet är någon annan siffra än de som menyn innehåller
            break;
    }
}

这是另一个class我的方法

public class Dog
{
    private String name;
    private String race;
    private int age;
    private double weight;
    private double tailLength;

    public Dog (String name, String race, int age, double weight)
    {
        this.name = name;
        this.setRace(race);
        this.age = age;
        this.weight = weight;

        if(race.equals("tax"))
        {
            this.setTailLength(3.7);
        }
        else
        {
            this.setTailLength((age - weight) / 10);
        }
    }


    public String getRace()
    {
        return race;
    }

    public void setRace(String race)
    {
        this.race = race;
    }

    public double getTailLength()
    {
        return tailLength;
    }

    public void setTailLength(double tailLength)
    {
        this.tailLength = tailLength;
    }

    public int increaseAge()
    {
        age++;
        return age;
    }

    public String toString()
    {
        return name + " " + getRace() +
                " " + age + " " + "år" + " " + weight + " " + "kg" + " " + getTailLength();
    }

    public String getName()
    {
        return name;
    }
}

为清楚起见,这是您目前拥有的:

            System.out.println("Name of dog:");
            String userInput3 = myscan.next();

            for(Dog d : doglist) 
            {
                if(d.getName().equals(userInput3)) 
                {
                    doglist.remove(d.toString());
                }
                else
                {
                    System.out.println("Can't find dog");
                }
            }

            break;

dogList 是一个 ArrayList<Dog>.

ArrayList.remove()documentation states:

Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged.

在这里,您使用参数 d.toString() 调用 remove()d 是您要删除的 Dog 实例。 d.toString() returns一个String.

因此 dogList.remove(d.toString()) 将尝试从列表中删除 String。显然这个 String 不在列表中,因为它是 Dog 的列表。此 String 将找不到,也不会删除任何内容。

如文档所述,您需要传递要删除的实例。您需要致电 doglist.remove(d)。然而,这会导致错误,因为您无法在迭代列表时从列表中删除项目。

因此,您需要将 Dog 实例存储在一个临时变量中,并在对其进行迭代后将其删除。

像这样的东西会起作用:

Dog dogToRemove = null;
for (Dog d: dogList) {
    if (d.getName().equals(userInput3)) {
        dogToRemove = d;
    }
}

if (dogToRemove == null) {
    System.out.println("Could not find dog with name " + userInput3);
} else {
    dogList.remove(dogToRemove);
}

请注意,还有其他方法可以做到这一点,这只是其中之一。我鼓励您找到替代方案,以便更好地了解它的工作原理。

对于案例 3:

  • 尝试添加一个 else 并将您的消息放在那里

            System.out.println("Name of dog:");
            String userInput2 = myscan.next();
    
            for (Dog d : doglist) {
                if (d.getName().equals(userInput2)) {
                    d.increaseAge();
                    break;
                }
                else {
                    System.out.println("Can't find dog");
                }
            }
    
            break;
    

对于情况 4:您可以通过索引删除

System.out.println("Name of dog:");
            String userInput3 = myscan.next();
            for (Dog d : doglist) {
                if (d.getName().equals(userInput3)) {
                    doglist.remove(doglist.indexOf(d));
                } else {
                    System.out.println("Can't find dog");
                }
            }
            break;

Java 8.

有更好的方法
doglist = doglist.stream().filter(dog -> !dog.getName().equals(userInput3)).collect(toList());

一行代码,易于阅读,没有移动部件

如果你想在找不到狗的情况下留言,那么:

if (doglist.stream().anyMatch(dog -> dog.getName().equals(userInput3)){
  doglist = doglist.stream().filter(dog -> !dog.getName().equals(userInput3)).collect(toList());
} else {
   System.out.println("Can't find dog");
}