0

I'm quite new to programming and I want to be able to prevent a duplicate String input from the user. But so far the code below does not work (or is completely ignored by the program). Thanks in advance!!

    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");
    }
M Ann
  • 107
  • 1
  • 9

1 Answers1

0

You can use 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;
}

Or you can use a SET. SET prevent duplicates by default. You can read about here 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;
    }
 }
cvdr
  • 939
  • 1
  • 11
  • 18