(显示三张牌)请写一个程序,显示从一副52张的扑克牌中随机选择的三张牌。牌的图像文件命名为1.png, 2.png,......,52.png,并保存在image/card 目录下。三张牌都是不同的并且是随机选择的。
书本上的提示是:可以这样随机选择牌,想将数字1~52保存在一个数组列表中,按照11.12节中介绍的方法进行一次随机洗牌,然后使用数组列表中前面三个数组作为图像的文件名。
问题:怎么使用数组列表中前面三个数组作为图像的文件名?
或者有没有其它的方法?
书本上的提示是:可以这样随机选择牌,想将数字1~52保存在一个数组列表中,按照11.12节中介绍的方法进行一次随机洗牌,然后使用数组列表中前面三个数组作为图像的文件名。
问题:怎么使用数组列表中前面三个数组作为图像的文件名?
或者有没有其它的方法?
for(int i = 0;i<52;i++){
imgs[i] = i+1;
}Random rand = new Random();
for(int i =0; i < 3; i++){
System.out.println("card file name :" + imgs[rand.nextInt(53)]+".png";
}
这个随机是有问题的,可能会取到相同的值
你自己可以根据Fisher–Yates shuffle 写一个程序打乱这个数组的次序
Set<Integer> imgIndex = new HashSet<Integer>();
getImgIndex(3, imgIndex);
System.out.println("抽取的牌是:");
for(Integer entity : imgIndex)
System.out.println(entity + ".png");
} private static void getImgIndex(int n, Set<Integer> imgIndex) {
for(int i = 0;i < n;i++){
int temp = new Random().nextInt(52) + 1;
imgIndex.add(temp);
}
if (imgIndex.size() < n)
getImgIndex(n - imgIndex.size(), imgIndex);
}
}