简体   繁体   English

用Java生成随机Long值

[英]Generating Random Long value in Java

I am trying to generate two 9 digit long random long value in Java using the below code: 我正在尝试使用以下代码在Java中生成两个9位长的随机long值:

for (int i =0;i<2;i++) {                
    String axisIdStr = Long.toString((long)(System.nanoTime() * (Math.random() * 1000)));
    System.out.println("@@@@@@@@ axisIdStr "+axisIdStr);
    String axId = axisIdStr.substring((axisIdStr.length() -9), axisIdStr.length()) ;
}

But when I run this in windows, i get two different numbers where as when run in mac, I get same two numbers. 但是当我在Windows中运行时,我得到两个不同的数字,而在Mac中运行时,我得到了两个相同的数字。 Why is this happening ? 为什么会这样呢? Can you suggest a better way to generate the long values? 您能建议一种更好的方法来生成长值吗?

According to your requirement you need to generate 9 digit random numbers. 根据您的要求,您需要生成9位随机数。 As in the comment suggested you can do it using random.Below I have just given one solution to generate random number between two numbers. 正如评论中所建议的那样,您可以使用random进行操作。下面我只给出了一种解决方案,可以生成两个数字之间的随机数。

long lowerLimit = 123456712L;
long upperLimit = 234567892L;
Random r = new Random();
long number = lowerLimit+((long)(r.nextDouble()*(upperLimit-lowerLimit)));

You could create an array a[] of int of size 9, and populate with random integers 0-9. 您可以创建一个大小为9的int数组a [],并使用随机整数0-9填充。 Then sum the array up multiplying accordingly. 然后将数组求和并相乘。

a[8]*1 + a[7]*10 + a[6]*100 ...

You need to make sure that a[0] only takes digits 1-9 tho... 您需要确保a [0]仅使用1到9之间的数字。

To get even more random sequence, you Ideally should work on Strings, then you would be able to get 0 on the start position of your random "string", it won't be a number. 为了获得更多的随机序列,理想情况下,您应该在Strings上工作,那么您将能够在随机“ string”的起始位置上获得0,而不会是数字。

Or maybe generate somthing pseudo random and strip last 9 digits out of it. 或者,可能会生成一些伪随机数据,并从中删除最后9位数字。

That's the DIY version of what you could accomplish with what's already out there... 这就是您可以使用现有功能完成的DIY版本...

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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