1 产生特定范围的随机整数
我们在之前的例子中都经常会使用到Math.random来产生随机数,Math.random产生[0,1.0)之间的double数。还有其他的例子如:
(int)(Math.random()*10) ; //产生[0,10)之间的随机数,也就是产生一个随机的一位数。
50+(int)(Math.random()*50) ; //产生[50,100)之间的随机整数,也就是50~99
更为一般的是, a+Math.random()*b ; //产生一个在[a,a+b)的随机数
所以,其实我们之前那个猜数的游戏中,产生一个二位数是随机数 最好的形式应该就是 10+(int)Math.random*90; 也就是产生了[10,100) 之间的随机整数了。
2 产生随机字符
every character has a unique Unicode between 0 and FFFF in
hexadecimal (65535 in decimal). To generate a random character is to generate a random inte-
ger between 0 and 65535 using the following expression (note that since 0 <= Math.ran-
dom() < 1.0, you have to add 1 to 65535):
(int)(Math.random() * (65535 + 1))
也就是说,每个字符有一个Unicode(0~65535)之间,那么使用前边的一般情况 a+Math.random()*b;产生 [a,a+b)之间的一个随机数,那么现在就是要产生 [0,6553], 那么就是在[0,65536)之间,所以使用(int) Math.random()*65536就产生了一个随机字符。
进一步,如果要产生a~z之间的一个随机字符呢? 同样的 就是(char)('a'+Math.random()*('z'-'a'+1));
更为一般的,要产生 ch1~ch2之间的一个随机字符 为(char)( ch1+Math.random()*(ch2-ch1+1));
看下面的例子,使用RandomChar类中的方法来产生各种不同的随机字符,并用一个TestRandomChar来测试结果
public class TestRandomChar
{
public static void main(String [] args)
{
final int NUM=3;
int i=0;
while(i<NUM)
{
System.out.print(RandomChar.getLowerCaseLetter());
System.out.print(RandomChar.getUpperCaseLetter());
System.out.print(RandomChar.getDigitalLetter());
System.out.print(RandomChar.getRandomLetter());
System.out.println();
++i;
}
}
}
class RandomChar
{
public static char getRandomChar(char ch1,char ch2)
{
return (char)(ch1+Math.random()*(ch2-ch1+1));
}
public static char getLowerCaseLetter()
{
return getRandomChar('a','z');
}
public static char getUpperCaseLetter()
{
return getRandomChar('A','Z');
}
public static char getDigitalLetter()
{
return getRandomChar('0','9');
}
public static char getRandomLetter()
{
return getRandomChar('\u0000','\uFFFF');
}
}