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");
    }
2
  • 2
    You need to search all of dogs, not just dogs(i) to validate for duplicates. Commented Jan 15, 2019 at 19:17
  • What is "auction" class? Commented Jan 15, 2019 at 19:37

1 Answer 1

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;
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.