在一副牌中,随机的抽出三张牌,这三张牌不能够重复。
import javax.swing.*;
import java.awt.*;
public class CardGame extends JFrame {
ImageIcon[] icons = new ImageIcon[3];
JLabel[] lbs = new JLabel[3];
public CardGame() {
int[] a = new int[3];
//产生三个不重复的随机数,每个数字对应着每一张牌
for(int i = 0; i < a.length; i++) {
int x = (int)(1 + Math.random() * 52);
for(int j = 0; j < i; j++) {
if(a[j] == x) {
x = (int)(1 + Math.random() * 52);
}
}
a[i] = x;
}
for(int i = 0; i < lbs.length; i++) {
icons[i] = new ImageIcon("image/card/" + a[i] + ".png");
lbs[i] = new JLabel(icons[i]);
}
setLayout(new GridLayout(1, 3, 1, 1));
add(lbs[0]);
add(lbs[1]);
add(lbs[2]);
}
public static void main(String[] args) {
JFrame frame = new CardGame();
frame.setTitle("扑克游戏");
frame.pack();
frame.setLocation(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
随机的抽出一副牌中的三张。
最新推荐文章于 2021-05-26 00:52:29 发布