我需要根据用户输入从 ArrayList 中删除一个元素。所以我有一个 ArrayList,用户可以在其中注册狗。然后,如果用户想要移除一只狗,他/她应该能够通过使用命令“移除狗”并后跟狗的名字来完成此操作。
我尝试过使用迭代器,但在使用它时仅使用 else 语句,并且屏幕上打印出“没有发生任何事情”。
import java.util.Iterator;
import java.util.Scanner;
import java.util.ArrayList;
public class DogRegister {
ArrayList<Dog> dogs = new ArrayList<>();
private Scanner keyboard = new Scanner(System.in);
public static void initialize() {
System.out.println("Welcome to this dog application");
}
private boolean handleCommand(String command) {
switch (command) {
case "One":
return true;
case "register new dog":
registerNewDog();
break;
case "increase age":
increaseAge();
break;
case "list dogs":
listDogs();
break;
case "remove dog":
removeDog();
break;
default:
System.out.println("Error: Unknown command");
}
return false;
}
private void registerNewDog() {
System.out.print("What is the dog's name? ");
String dogNameQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("Which breed does it belong to? ");
String dogBreedQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("How old is the dog? ");
int dogAgeQuestion = keyboard.nextInt();
System.out.print("What is its weight? ");
int dogWeightQuestion = keyboard.nextInt();
keyboard.nextLine();
Dog d = new Dog(dogNameQuestion, dogBreedQuestion, dogAgeQuestion,
dogWeightQuestion);
dogs.add(d);
System.out.println(dogs.get(0).toString());
}
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();
dogsIterator.hasNext();) {
if (removeDogList.equals(dogsIterator)) {
System.out.println("The dog has been removed ");
break;
} else {
System.out.println("Nothing has happened ");
break;
}
}
}
public void closeDown() {
System.out.println("Goodbye!");
}
public void run() {
initialize();
runCommandLoop();
}
public static void main(String[] args) {
new DogRegister().run();
}
}
最佳答案
正如 JB Nizet 所说,您将 String
与 Iterator
进行比较:
if (removeDogList.equals(dogsIterator)) {
它永远不会返回true
。
此外,即使在迭代器上调用 next()
也无法解决问题,因为 String
也不能等于 Dog
对象。
相反,当您使用 equals()
并调用 Iterator.remove()
时,将 String
与 String
进行比较,以有效地删除当前迭代的元素。
应该没问题:
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();dogsIterator.hasNext();) {
Dog dog = dogsIterator.next();
if (removeDogList.equals(dog.getName())) {
dogsIterator.remove();
System.out.println("The dog has been removed");
return;
}
}
System.out.println("Nothing has been removed");
}
关于java - 使用用户输入和迭代器从 ArrayList 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54050892/