java數組隨機
發布時間: 2024-08-04 12:35:18
⑴ java怎麼使用隨機抽取數組里的數據
package reptile;
import java.util.Random;
public class Test
{
public static void main(String[] args){
String[] b = {"公共的", "私有的", "受保護的"};
Random rand = new Random();
int num = rand.nextInt(3);
System.out.println(b[num]);
}
⑵ java涓濡備綍闅忔満浜х敓涓涓鎸囧畾鏁扮粍涓鐨勬暟
1銆佽幏鍙栨暟緇勯暱搴
intarr[]={1,2,3,4,5};//瀹氫箟涓涓鏁扮粍
intlen=arr.length;//鑾峰彇鏁扮粍闀垮害緇欏彉閲弆en
2銆佹牴鎹鏁扮粍闀垮害錛屼嬌鐢≧andom闅忔満鏁扮粍鐨勭儲寮曞
Randomrandom=newRandom();//鍒涘緩闅忔満瀵硅薄
intarrIdx=random.nextInt(len-1);//闅忔満鏁扮粍緔㈠紩錛宯extInt(len-1)琛ㄧず闅忔満鏁存暟[0,(len-1)]涔嬮棿鐨勫
3銆佹牴鎹闅忔満緔㈠紩鑾峰彇鏁扮粍鍊
intnum=arr[arrIdx];//鑾峰彇鏁扮粍鍊
⑶ Java緙栫▼,鍒涘緩涓涓浜岀淮鏁扮粍,闅忔満浜х敓 0∼100涔嬮棿鐨勫,奼傚嚭鏈澶у煎強瀵瑰簲涓嬫爣
闇奼傦細Java緙栫▼,鍒涘緩涓涓浜岀淮鏁扮粍,闅忔満浜х敓 0鍀100涔嬮棿鐨勫,奼傚嚭鏈澶у煎強瀵瑰簲涓嬫爣銆
鍒嗘瀽姝ラわ細
A錛氬壋寤轟竴涓浜岀淮鏁扮粍
int[][] twoArr = new int[8][8];
B: 闅忔満浜х敓0~100涔嬮棿鐨勫
Random random=new Random();
random.nextInt(100);
C:灝嗛殢鏈轟駭鐢熺殑鍊艱祴鍊肩粰鏁扮粍鍏冪礌
榪愮敤for寰鐜
D錛氭眰鍑烘渶澶у
鍋囪総woArr[0][0]涓烘渶澶у礆紝閬嶅巻鏁扮粍錛屼袱涓ゆ瘮杈冿紝鎶婂煎ぇ鐨勮祴鍊肩粰max銆傚悓鏃舵爣璁皒,y
E:杈撳嚭鏈澶у礆紝杈撳嚭x,y錛堥亶鍘嗙殑涓や釜灞閮ㄥ彉閲忥級鍊
importjava.util.Random;
classTwoArr{
publicstaticvoidmain(String[]args){
intn=8;//榪欓噷涔熷彲浠ユ敼鎴愰敭鐩樺綍鍏ョ殑褰㈠紡
int[][]twoArr=newint[n][n];//瀹氫箟浜岀淮鏁扮粍
//灝嗛殢鏈轟駭鐢熺殑鍊艱祴鍊肩粰鏁扮粍鍏冪礌
for(intx=0;x<twoArr.length;x++){
for(inty=0;y<twoArr[x].length;y++){
Randomrandom=newRandom();
twoArr[x][y]=random.nextInt(100);
}
}
//奼傛渶澶у煎拰緔㈠紩
intmax=twoArr[0][0];
intindex1=0;
intindex2=0;
for(intx=1;x<twoArr.length;x++){
for(inty=0;y<twoArr[x].length;y++){
if(twoArr[x][y]>max){
max=twoArr[x][y];
index1=x;
index2=y;
}
}
}
//杈撳嚭
System.out.println("鏈澶у兼槸錛"+max+",鍏朵笅鏍囦負錛歔"+index1+"]"+"["+index2+"]");
}
}
熱點內容