java 怎么实现任意生成一个10位数?
2个回答
展开全部
/**
* 生成随机数字
* @param length
* @return
*/
public static final String randomNumber(int length) {
char[] numbersAndLetters = null;
java.util.Random randGen = null;
if (length < 1) {
return null;
}
// Init of pseudo random number generator.
if (randGen == null) {
if (randGen == null) {
randGen = new java.util.Random();
// Also initialize the numbersAndLetters array
numbersAndLetters = ("0123456789").toCharArray();
}
}
// Create a char buffer to put random letters and numbers in.
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(9)];
}
return new String(randBuffer);
}
* 生成随机数字
* @param length
* @return
*/
public static final String randomNumber(int length) {
char[] numbersAndLetters = null;
java.util.Random randGen = null;
if (length < 1) {
return null;
}
// Init of pseudo random number generator.
if (randGen == null) {
if (randGen == null) {
randGen = new java.util.Random();
// Also initialize the numbersAndLetters array
numbersAndLetters = ("0123456789").toCharArray();
}
}
// Create a char buffer to put random letters and numbers in.
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(9)];
}
return new String(randBuffer);
}
更多追问追答
追问
能给解说的详细点吗,帮帮忙啦!谢谢。
追答
你直接调用这个方法就行了 。呵呵,你可以试一下的哦。。。。细心的看看就明白了,其实很简单的。就是创建一个char数组,从数组中随机的取出length长度的数字,转成string即可
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询