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);
}如何确保只存储具有唯一id的客户。例如,如果客户A获得id "AB-1",那么客户B应该有一个与"AB-8“不同的id。我试图使用Hashset,但是我不确定这是解决这个问题的正确方法。我不认为我需要使用UIDD。
发布于 2017-04-27 02:46:23
考虑这个解决方案
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;
}
}关键是set是一个字段,并使用contains进行检查。
发布于 2017-04-27 02:24:25
地点
while(set.contains(number)){ number = customer.generateCustomerID("AB", 1); }先于set.add(number);customer.setCustomerID(number);
https://stackoverflow.com/questions/43647505
复制相似问题