3 回答

TA貢獻1859條經(jīng)驗 獲得超6個贊
嘗試在任何循環(huán)內(nèi)的數(shù)組中初始化數(shù)組,例如:
int articles[][] = new int[50][];
for (int i = 0; i < 50; i++) {
articles[i] = new int[(int) Math.floor(Math.random() * 30 + 1)];
}

TA貢獻1942條經(jīng)驗 獲得超3個贊
我建議您研究 中的實用方法java.util.Arrays。它是處理數(shù)組的輔助方法的金礦。從 1.8 開始就有了這個:
int articles[][] = new int[50][];
Arrays.setAll(articles, i -> new int[(int)Math.floor(Math.random() * 30 + 1)]);
在這個問題案例中,使用 lambda 并不比普通循環(huán)更有效,但通??梢蕴峁└啙嵉恼w解決方案。
我還建議不要自行擴展double(int請參閱來源Random.nextInt()并自行決定)。
Random r = new Random();
int articles[][] = new int[50][];
Arrays.setAll(articles, i -> new int[r.nextInt(30)]);

TA貢獻1851條經(jīng)驗 獲得超4個贊
要創(chuàng)建一個行數(shù)恒定但行長度隨機的數(shù)組,并用隨機數(shù)填充它:
int rows = 5;
int[][] arr = IntStream
.range(0, rows)
.mapToObj(i -> IntStream
.range(0, (int) (Math.random() * 10))
.map(j -> (int) (Math.random() * 10))
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
[3, 8]
[2, 7, 6, 8, 4, 9, 3, 4, 9]
[5, 4]
[0, 2, 8, 3]
[]
添加回答
舉報