亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

Java List:調用Arrays.fill()填充數組時,為什么會出現一些意想不到的元素?

Java List:調用Arrays.fill()填充數組時,為什么會出現一些意想不到的元素?

慕尼黑5688855 2021-09-29 15:30:47
我是一個初級程序員,第一次在這里提問,如果對格式有任何擔心,我會感到非常抱歉。首先,感謝您的回答、耐心和原諒。實際上問題是“循環直到找到 4 張不同顏色的撲克牌”。我使用一個數組來表示卡號,并使用一個數組來表示它們的顏色。并且我用for語句填充cardNo數組,值從1到4,但顯示為0,不知道為什么,我想這就是問題發生的地方,這就是我的全部代碼。public static void collect() {    int num=0;    //represent 52 Poker Cards    int [] cardNo=new int[52];    List list=new ArrayList<>();    // `int[] color=new int[4]` to represent 4 colors, so the value     // of cardNo[] elements is the Color.    for(int i=0;i<4;i++) {        Arrays.fill(cardNo, i*13, (i+1)*13-1, i+1);    }    for(int n:cardNo) {        list.add(n);    }    Collections.shuffle(list);    // I use this for statement to check if it's worry with Arrays.fill(),    // or it's about the list.add().    for(int i:cardNo) {        System.out.print(i+" ");    }    System.out.println(list);    /*int[] color=new int[4];    while(color[0]==0||color[1]==0||color[2]==0||color[3]==0) {        int n=(int)(Math.random()*53);        color[(int) list.get(n)-1]++;        num++;    }    System.out.println("Number of picks: "+num);*/}
查看完整描述

1 回答

?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

toIndex參數Arrays.fill是獨占的,所以改成:

Arrays.fill(cardNo, i*13, (i+1)*13 - 1, i+1);

Arrays.fill(cardNo, i*13, (i+1)*13, i+1);

Javadoc:

void java.util.Arrays.fill(int[] a, int fromIndex, int toIndex, int val)

將指定的 int 值分配給指定整數數組的指定范圍內的每個元素。要填充的范圍從 index fromIndex,inclusive 擴展到 index toIndex,exclusive。(如果 fromIndex==toIndex,則要填充的范圍為空。)


查看完整回答
反對 回復 2021-09-29
  • 1 回答
  • 0 關注
  • 256 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號