在JAVA中 怎样获得一个随机数及字符?
3个回答
展开全部
import java.util.Random;
public class Stat {
public static void main(String[] args) {
// Math.random() 获取0~1之间的double类型数值
int num = (int)(Math.random()*100); // 获取0~100之间的整数
System.out.println(num);
System.out.println(getRandomString(12));
}
// 获取随机字符串
public static String getRandomString(int length) { // length 字符串长度
StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
StringBuffer sb = new StringBuffer();
Random r = new Random();
int range = buffer.length();
for (int i = 0; i < length; i ++) {
sb.append(buffer.charAt(r.nextInt(range)));
}
return sb.toString();
}
}
public class Stat {
public static void main(String[] args) {
// Math.random() 获取0~1之间的double类型数值
int num = (int)(Math.random()*100); // 获取0~100之间的整数
System.out.println(num);
System.out.println(getRandomString(12));
}
// 获取随机字符串
public static String getRandomString(int length) { // length 字符串长度
StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
StringBuffer sb = new StringBuffer();
Random r = new Random();
int range = buffer.length();
for (int i = 0; i < length; i ++) {
sb.append(buffer.charAt(r.nextInt(range)));
}
return sb.toString();
}
}
参考资料: http://blog.csdn.net/xzknet/article/details/1930777
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询