[英]java: generating random numbers in a loop
I'm not sure my use of the Random class is right--perhaps I am misinterpreting it. 我不确定我对Random类的使用是对的 - 也许我误解了它。 (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:
以下是我的代码,下面是用于测试while子句的真实性的方法:
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. 会发生什么是错误日志显示pk = 13(或某事)然后它无限地重复该消息。 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?
或者唯一的解释是select方法返回相同的结果而不查看新参数? Maybe a caching issue?
也许是一个缓存问题? This is on tomcat/MS SQL.
这是在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. 在第一次设置
x_invoice_num
值之后,它将永远不再为null,因此它永远不会更新。 i think you don't want the put()
to be conditional at all. 我认为你不希望
put()
完全有条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.