作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我是一个初学者,第一次在这里提问,如果有格式上的问题,真的很抱歉。首先,感谢您的回答、耐心和原谅。
实际上问题是“循环直到找到 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.fill
的toIndex
参数是独占的,所以改成:
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)
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.)
关于Java List : When I call Arrays. fill()填充一个数组,为什么会出现一些意想不到的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52419824/
我是一名优秀的程序员,十分优秀!