二.定义一张牌
===========
public class Card {
public char suit; //花色
public String rank; //面值
public Card(char suit, String rank) {
this.suit = suit; //构造方法
this.rank = rank;
}
@Override
public String toString() { //重写打印方法
return “[”+suit+“:”+rank+“]”;
}
}
说明:一张牌有花色和面值,花色包括红桃方片那些,所以给的是字符类型,面值包含A,J,Q,K,所以给的字符串类型。
三. 程序主体
========
说明:我把程序主体全放到CardGame类中
3.1 定义一副新牌
public List getCards(){
char[] suits = {‘♥’,‘♠’,‘♦’,‘♣’}; //花色数组
String[] ranks = {“A”,“2”,“3”,“4”,“5”,“6”,“7”,“8”,“9”,“10”,“J”,“Q”,“K”};//面值数组
List cards = new ArrayList<>(52);//定义数组列表来存放每一张牌,并给出数量
for(int i=0;i<4;i++){
for(int j=0;j<13;j++){
cards.add(new Card(suits[i],ranks[j])); //向列表中添加定义好的牌
}
}
return cards; //返回这幅牌
}
3.2 定义洗牌方法
必看视频!获取2024年最新Java开发全套学习资料 备注Java
public void shuffle(List cards){
Random random = new Random(); //获取随机数种子
for(int i=cards.size()-1;i>0;i–){
int j = random.nextInt(i);
swap(cards,i,j); //依次将最后一张牌与随机一张牌交换顺序
}
}
public void swap(List cards,int i,int j){ //交换方法swap
Card temp = cards.get(i);
cards.set(i,cards.get(j));
cards.set(j,temp);
}
3.3 定义三个人和抓牌过程
说明:我把这个过程放在主方法中
List<List> hands = new ArrayList<>(3); //定义三个人
hands.add(new ArrayList<>(13));
hands.add(new ArrayList<>(13)); //每个人都需要揭13张牌
hands.add(new ArrayList<>(13));
// 三个人依次揭牌,每个人揭最上面的牌,揭到后就将它从牌的列表里消除,
// 也就是消除最上面的牌一次给每个人
for(int i=0;i<13;i++){
for(int j=0;j<3;j++){
hands.get(j).add(cards.remove(0));
}
}
四. 输出每个人抓到的牌
=============
System.out.println(“A手中的牌:”);
System.out.println(hands.get(0));
System.out.println(“B手中的牌”);
System.out.println(hands.get(1));
System.out.println(“C手中的牌”);
System.out.println(hands.get(2));
五.全部代码展示和输出结果展示
================
代码展示:
最后
我还通过一些渠道整理了一些大厂真实面试主要有:蚂蚁金服、拼多多、阿里云、百度、唯品会、携程、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。
还有专门针对JVM、SPringBoot、SpringCloud、数据库、Linux、缓存、消息中间件、源码等相关面试题。
、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。**
[外链图片转存中…(img-1X3jUHFA-1716449148631)]
还有专门针对JVM、SPringBoot、SpringCloud、数据库、Linux、缓存、消息中间件、源码等相关面试题。
[外链图片转存中…(img-YGkrEnyg-1716449148632)]