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+"]");
}
}
热点内容