java只有涉及到隨機的,最經常用到的方法就是Math.random(),這個方法會返回一個大於0小於1的隨機數( 能取0不能取1 ),如果我們要隨機0-9,就可以用(Math.random()*10)來表示,隨機0-99也類似如此操作。
一:隨機獲取0-66代碼實例:
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("隨機獲取0-66中的一個數:" + (int)(Math.random()*67));;
}
}
測試結果:
隨機獲取0-66中的一個數:47
隨機獲取0-66中的一個數:11
隨機獲取0-66中的一個數:19
隨機獲取0-66中的一個數:49
隨機獲取0-66中的一個數:53
隨機獲取0-66中的一個數:20
隨機獲取0-66中的一個數:66
隨機獲取0-66中的一個數:57
隨機獲取0-66中的一個數:20
隨機獲取0-66中的一個數:61
二:有時候,我們想隨機獲取的不是數字,而是字母,這時候我們要用到char
先看看char前兩百個都是哪些
字符,執行以下代碼:
public static void main(String[] args) {
for(int i =0; i<200; i++){
char c = (char)i ;
System.out.print(i + ":" + c + " ");
if (i%10 == 0) {
System.out.println();
}
}
}
結果:
由上圖可以發現,大寫字母A--Z是從65-90 ,小寫字母a--z是從97--122 , 所以如果要隨機取一個字符的話可以用以下代碼:
public static void main(String[] args) {
char c=(char)(int)(Math.random()*26+97);
System.out.println("隨機取一個小寫字母:" + c);
c=(char)(int)(Math.random()*26+65);
System.out.println("隨機取一個大寫字母:" + c);
}
結果:
隨機取一個小寫字母:n
隨機取一個大寫字母:A
三:有時候,我們想要隨機的中一堆字符和數字和符號裏面隨機獲取一個
代碼實例(一堆數據中隨機取10個):
public static void main(String[] args) {
//先定義取值範圍
String chars = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz!~@#$%^&*()_+-=`[]{};':,.<>/?|";
StringBuffer value = new StringBuffer();
for (int i = 0; i < 10; i++) {
value.append(chars.charAt((int)(Math.random() * 92)));
}
System.out.println("隨機選取的10個數爲:" + value.toString());
}
結果:
隨機選取的10個數爲:a8sLv0wK24