关于生成唯一的随机数

问题描述:

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应该具有不同的ID,如“AB-8”。我试图使用Hashset,但我不确定这是解决此问题的正确方法。我不认为我需要使用UIDD。关于生成唯一的随机数

+1

你有一个问题检查之前制作独特的ID或使用的集合存在问题? – failedProgrammer

+0

这些客户最终是否存储在数据库中?他们需要什么范围才是唯一的? –

+0

我在制作独特的ID时遇到了问题。 –

考虑这种解决方案

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

+0

我明白了。这段代码是否只是检查id是否已被使用? –

+0

是的,'如果(taken.contains(id)){' –

+0

我试过你的代码,但我不知道如何将ID存储到客户。 –

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

+0

也许'!contains'? –

+0

对不起,应该是'contains(number)'。但是我的答案有什么问题? – wylasr

+0

该代码仍然给我重复的客户ID。 –