繁体   English   中英

Java List:当我调用Arrays.fill()来填充数组时,为什么它会出现一些意想不到的元素?

[英]Java List: When I call Arrays.fill() to fill an array, why it will appear some unexpected elements?

我是初学者程序员,这是我第一次在这里提问,如果对格式有任何担心,我会感到非常抱歉。 首先,感谢您的回答,感谢您的耐心和赦免。

实际上问题是“循环直到找到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);*/
}

Arrays.filltoIndex参数是独占的,因此更改:

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值分配给指定的int数组的指定范围的每个元素。 要填充的范围从索引fromIndex(包括)扩展到索引toIndex,exclusive (如果fromIndex == toIndex,则要填充的范围为空。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM