0
  public String generateCustomerID(String id, int digit)//Customer Class

   randomGenerator = new Random();

   String index = "";

   for(int i = 1; i <= digit; i++)
   {  

       index +=  randomGenerator.nextInt(10);

   }
      return id + index;

   public void storeCustomer(Customer customer)//Shop Class
   {
    customerList.add(customer);
    HashSet<String> set = new HashSet<>();
    String number =   customer.generateCustomerID("AB", 1);

    set.add(number);
    customer.setCustomerID(number);

   }

How can i make sure that only customers with unique id are stored. For example, if customer A got id "AB-1", then customer B should have a different id like "AB-8". I tried to use Hashset but but i am not sure this is the right method to solve this problem. I do not think i need to use UIDD.

2 Answers2

0

consider this solution

    static Set<String> taken = new HashSet <>();
    public static void main(String [] args)
    {
        Scanner scan = new Scanner (System.in);
        while (true) {
            System.out.println("enter id ");
            String id = scan.nextLine();
            if (taken.contains(id)) {
                System.out.println("already taken");
                continue;
            }
            taken.add (id);
            System.out.println("another [y/n]? ");
            if (scan.nextLine().equals("n"))
                break;
        }
    }

the key point being that set is a field and it is checked using contains

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
-3

place
while(set.contains(number)){ number = customer.generateCustomerID("AB", 1); } before set.add(number);customer.setCustomerID(number);

wylasr
  • 117
  • 9