如何在java中生成一个4位数的随机长?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33577737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to generate a random long with 4 digits in java?
提问by Louise Lin
how to generate a long that is in the range of [0000,9999] (inclusive) by using the random class in java? The long has to be 4 digits.
java - 如何使用java中的随机类生成[0000,9999](含)范围内的long?long 必须是 4 位数字。
采纳答案by Grogi
If you want to generate a number from range [0, 9999], you would use random.nextInt(10000)
.
如果要生成范围 [0, 9999] 中的数字,可以使用random.nextInt(10000)
.
Adding leading zeros is just formatting:
添加前导零只是格式化:
String id = String.format("%04d", random.nextInt(10000));
回答by Elliott Frisch
A Java int
will never have leading 0
(s). You'll need a String
for that. You could use String.format(String, Object...)
or (PrintStream.printf(String, Object...)
) like
Javaint
永远不会有前导0
。你需要一个String
。你可以使用String.format(String, Object...)
或 ( PrintStream.printf(String, Object...)
) 喜欢
Random rand = new Random();
System.out.printf("%04d%n", rand.nextInt(10000));
The format String
%04d
is for 0 filled 4 digits. And Random.nextInt(int)
will be [0,10000) or[0,9999].
格式String
%04d
为 0 填充的 4 位数字。并且Random.nextInt(int)
将是 [0,10000)或[0,9999]。