java7: 使用隨進函數產生特定範圍的隨機整數及隨機字符

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');
	}
}



發佈了112 篇原創文章 · 獲贊 15 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章