第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Java中創(chuàng)建具有隨機長度列的多維數(shù)組?

如何在Java中創(chuàng)建具有隨機長度列的多維數(shù)組?

一只斗牛犬 2024-01-25 21:39:56
我需要在 Java 中創(chuàng)建一個多維數(shù)組,但列的長度是隨機的。例如,假設隨機長度為 3、2、4 和 1,那么我們會有這樣的結果:[[1, 2, 3], [1, 2], [3, 4, 5, 6], [3]]我已經(jīng)嘗試過這個,但它不會為每列創(chuàng)建隨機長度:int articles[][] = new int[50][(int) Math.floor(Math.random() * 30 + 1)];有誰知道如何實現(xiàn)這一目標?注意:數(shù)組始終有 50 行,我只需要每一列都是隨機的。
查看完整描述

3 回答

?
慕絲7291255

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)];

}


查看完整回答
反對 回復 2024-01-25
?
手掌心

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)]);


查看完整回答
反對 回復 2024-01-25
?
繁花不似錦

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]

[]


查看完整回答
反對 回復 2024-01-25
  • 3 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號