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());
?}
}
?
?