我对编程还很陌生,所以我希望能够防止用户输入重复的String。但是到目前为止,下面的代码不起作用(或被程序完全忽略了)。在此先感谢!
boolean current = false;
for (int i = 0; i < dogs.size(); i++) {
System.out.println("Dog name: ");
String dogName = scan.nextLine().toLowerCase();
if (dogName.equals(dogs.get(i).getName())) {
auction.add(new auction(dogName));
System.out.printf(dogName + " has been put up for auction in auction #%d", i);
System.out.println();
current = true;
}//code below does not work
if (auction.contains(dogName)) {
System.out.println("Error: this dog is already up for auction.");
}
}
if (current == false) {
System.out.println("Error: no such dog in the register");
}
答案 0 :(得分:0)
您可以使用lambda
boolean hasThisDog = dogs.stream().anyMatch(d -> dogName.equals(d.getName()));
if(hasThisDog){
System.out.println("Error: this dog is already up for auction.");
}else{
auction.add(new auction(dogName));
System.out.printf(dogName + " has been put up for auction in auction #%d", i);
System.out.println();
current = true;
}
或者您可以使用SET。 SET默认情况下防止重复。您可以在这里Java: Avoid inserting duplicate in arraylist
了解更多信息Set<Dog> set = new HashSet<Dog>();
set.add(foo);
set.add(bar);
public class Dog{
@Override
public boolean equals(Object obj) {
if (obj instanceof Dog)
return (this.name= obj.name)
else
return false;
}
}