简体   繁体   中英

java: generating random numbers in a loop

I'm not sure my use of the Random class is right--perhaps I am misinterpreting it. (I've seen this usage many times, however, in my Googles.)

I'm trying to generate unique invoice numbers by concatenating a random number and a string, looking up that invoice in the database to see if it exists, and if it does then create a new invoice number and try again. Following is my code, and below that the method used to test the truthfulness of the while clause:

String iname = "foo";
int sequence = 0;
String invoice_name = "";
Random generator = new Random();
do {
  sequence = generator.nextInt( 1000 );
  invoice_name = iname + String.format("%03d", sequence);
} while( !isUniqueInvoiceName( invoice_name, params, qb )

// QueryBatch is just a caching mechanism and batch committer for queries
private boolean isUniqueInvoiceName(String invoice_name, HashMap params, QueryBatch qb) {
  if( params.get("x_invoice_num") == null ) params.put( "x_invoice_num",invoice_name );
  // Invoice.select returns the primary key of the top 1 invoices found, or 0 if none found.
  int pk = Invoice.select(params, qb);
  System.out.println("============= pk = " + pk + " =============");
  return ( pk == 0 );
}

What happens is that the error log shows pk = 13 (or something) and then it repeats that message infinitely. I can't see why. Is a new random number not being generated? Or is the only explanation that the select method is returning the same results without looking at the new parameters? Maybe a caching issue? This is on tomcat/MS SQL.

i think the problem is with this line:

if( params.get("x_invoice_num") == null ) params.put( "x_invoice_num",invoice_name );

after the first time you set the x_invoice_num value it will never be null again so it will never update. i think you don't want the put() to be conditional at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM