Class Random的常用的Method:
nextInt
()
nextInt
(int n)
nextBytes(byte[] bytes)
nextDouble()
nextFloat()
nextLong
()
nextBoolean
()
由于Random类中没有nextChar(),nextString()这样的方法,所以要随机产生一个字符或字符串应该自己手动编写Code
下面的例子就是一个自动产生字符的类:
import java.util.*;
public class RandomChar{
private static Random rand=new Random();
private static String source="ABCEDFGHIGKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxuyz";
private static char[] sur=source.toCharArray();
public static char nextChar(){
return sur[rand.nextInt(source.length())];
}
public static void main(String args[])
{
System.out.println(nextChar());
}
}
再编写一个随机产生字符串的类:
import java.util.*;
public class RandomString{
private static Random rand=new Random();
private static int len;//字符串的长度
public RandomString(int len){ this.len=len;}
private static String source="ABCEDFGHIGKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxuyz";
private static char[] sur=source.toCharArray();
public static char nextChar(){
return sur[rand.nextInt(source.length())];
}
private static String nextString(){
char [] buf=new char[len];
for(int i=0;i<len;i++)
buf[i]=nextChar();
return new String(buf);}
public static void main(String args[])
{
RandomString randStr=new RandomString(5);
System.out.println(randStr.nextString());
}
}