Java 随机数
一.java.lang.Math.random()
public class RandomTest{
public static void main(String[] args){
double a=Math.random();//random()会自动产生一个[0,1)的双精度随机数
System.out.println(a);
a=Math.random()*1000;//产生[0,1000)的双精度随机数
System.out.println(a);
int b=(int)(Math.random()*1000);//产生[0,1000)的整数随机数
System.out.println(b);
}
}
二.创建java.util.Random对象
import java.util.random
public class RandomTest{
public static void main(String[] args){
Random random=new Random();//创建random对象
int intNumber=random.nextInt();//获取一个整型数
float floatNumber=random.nextFloat();//获取一个浮点数[0,1)
double doubleNumber=random.nextDouble();//获取双精度数[0,1)
boolean booleanNumber=random.nextBoolean();//获取boolean数
System.out.println("intNumber:"+intNumber);
System.out.println("floatNumber:"+floatNumber);
System.out.println("doubleNumber:"+doubleNumber);
System.out.println("booleanNumber:"+booleanNumber);
int num = random.nextInt(100); //产生[0,100)随机数,只有nextInt()才有限制数字的使用
System.out.println(num);
}
}
package com.itqy8.util; import java.util.Random; public class GenerateRandomUtils { /** * 生成固定长度的随机字符 * @param len * @return */ public static String generateRandomChar(Integer len) { // 生成字母A-Z,a-z 之间的随机字符 StringBuffer sb = new StringBuffer(); for (Integer i = 0; i < len; i++) { int intRand = (int) (Math.random() * 52); char base = (intRand < 26) ? 'A' : 'a'; char c = (char) (base + intRand % 26); sb.append(c); } return sb.toString(); } /** * 生成固定长度的随机字符和数字 * @param len * @return */ public static String generateRandomCharAndNumber(Integer len) { StringBuffer sb = new StringBuffer(); for (Integer i = 0; i < len; i++) { int intRand = (int) (Math.random() * 52); int numValue = (int) (Math.random() * 10); char base = (intRand < 26) ? 'A' : 'a'; char c = (char) (base + intRand % 26); if(numValue%2==0){ sb.append(c); }else{ sb.append(numValue); } } return sb.toString(); } public static String getCharAndNumr(Integer length) { StringBuffer sb = new StringBuffer(); Random random = new Random(); for (int i = 0; i < length; i++) { String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字 if ("char".equalsIgnoreCase(charOrNum)){// 字符串 int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母 sb.append((char) (choice + random.nextInt(26))); } else if ("num".equalsIgnoreCase(charOrNum)){// 数字 sb.append(String.valueOf(random.nextInt(10))); } } return sb.toString(); } public static void main(String[] args) { //System.out.println(generateRandomChar(100)); for(int i=0;i<10;i++){ System.out.println(generateRandomCharAndNumber(20)); } } }