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

Wellen :

I am a beginner programmer, and it's my first time to ask a question here, if there is any worry about the format, I will feel really sorry. And at first, thank you for your answer, for your patience, and your pardon.

Actually the question is "loop until you find 4 different color Poker Cards". And I use an array to represent the Cards No, and an array to represent their Color. and I fill the cardNo array by a for statement, the value is from 1 to 4, but it appears 0, I don't know why, and I think that is where the problem happened, and this is all my code.

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);*/
}
Eran :

The toIndex parameter of Arrays.fill is exclusive, so change:

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

to

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

The Javadoc:

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

Assigns the specified int value to each element of the specified range of the specified array of ints. The range to be filled extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, therange to be filled is empty.)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92368&siteId=1