分析:
首先,创建两个集合color和num,存放花色和牌的大小。
用Collections.addAll添加花色和牌的大小到集合中。
ArrayList
color=new ArrayList ();
ArrayListnum=new ArrayList ();
Collections.addAll(color,"♥","♠","♣","♦");
Collections.addAll(num,"A","2","3","4","5","6","7","8","9","10","J","Q","K");
第二步,创建poker集合,用两个循环嵌套拼接花色和牌的大小到poker集合中,每循环一次就添加一个。最后把大小王单独添加到poker集合中。用Collections.shuffle(poker);打乱集合顺序。
ArrayList
poker=new ArrayList ();
for(int i=0;i{
for(int j=0;j{
poker.add(color.get(i)+num.get(j));
}
}
poker.add("大王");
poker.add("小王");Collections.shuffle(poker);
第三步,创建三位玩家的手牌集合,用循环把poker集合的前51的索引元素通过取余的方法平均添加到每位玩家的手牌集合中。
ArrayList
play1=new ArrayList ();
ArrayListplay2=new ArrayList ();
ArrayListplay3=new ArrayList ();
for(int i=0;i<51;i++)
{
if(i%3==0)
{
play1.add(poker.get(i));
}
else if(i%3==1)
{
play2.add(poker.get(i));
}
else {
play3.add(poker.get(i));
}
}
第四步, 随机数生成地主,并且把剩下三张牌添加到对应的玩家手牌集合中。最后打印玩家手牌信息。
Random r=new Random();
int moster=r.nextInt(3)+1;
switch (moster) {
case 1: {
System.out.println("玩家一没头脑抢到了地主");
Collections.addAll(play1, poker.get(51),poker.get(52),poker.get(53));
break;
}
case 2: {
System.out.println("玩家二不开心抢到了地主");
Collections.addAll(play2, poker.get(51),poker.get(52),poker.get(53));
break;
}
default: {
System.out.println("玩家三不聪明抢到了地主");
Collections.addAll(play3, poker.get(51),poker.get(52),poker.get(53));
break;
}
}
System.out.println("玩家一没头脑的牌有"+play1);
System.out.println("玩家二不开心的牌有"+play2);
System.out.println("玩家三不聪明的牌有"+play3);
}
}
代码结果如下:
完整代码:
package act;
import java.util.*;
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList
ArrayList
Collections.addAll(color,"♥","♠","♣","♦");
Collections.addAll(num,"A","2","3","4","5","6","7","8","9","10","J","Q","K");
ArrayList
for(int i=0;i
for(int j=0;j
poker.add(color.get(i)+num.get(j));
}
}
poker.add("大王");
poker.add("小王");
Collections.shuffle(poker);
ArrayList
ArrayList
ArrayList
for(int i=0;i<51;i++)
{
if(i%3==0)
{
play1.add(poker.get(i));
}
else if(i%3==1)
{
play2.add(poker.get(i));
}
else {
play3.add(poker.get(i));
}
}
Random r=new Random();
int moster=r.nextInt(3)+1;
switch (moster) {
case 1: {
System.out.println("玩家一没头脑抢到了地主");
Collections.addAll(play1, poker.get(51),poker.get(52),poker.get(53));
break;
}
case 2: {
System.out.println("玩家二不开心抢到了地主");
Collections.addAll(play2, poker.get(51),poker.get(52),poker.get(53));
break;
}
default: {
System.out.println("玩家三不聪明抢到了地主");
Collections.addAll(play3, poker.get(51),poker.get(52),poker.get(53));
break;
}
}
System.out.println("玩家一没头脑的牌有"+play1);
System.out.println("玩家二不开心的牌有"+play2);
System.out.println("玩家三不聪明的牌有"+play3);
}
}