一、使用类
1、LinkList类
add(E e) 将指定元素添加到此列表的结尾。
get(int index) 返回此列表中指定位置处的元素。
size() 返回此列表的元素数。
2、Object类
toString() 重写toString使println()方法直接输出对象信息
contains(Object o) 如果此列表包含指定元素,则返回 true。
3、Random类
- nextInt(int n) 返回一个 0(包括)到n(不包括)之间 int 值随机数。
二、代码
import java.util.*;
//需求:使用LinkedList存储一副扑克牌(52张),并且实现洗牌功能
class poker
{
public poker(String color, String num)
{
super();
this.color = color;
this.num = num;
}
String color;
String num;
public String toString()
{
return color+num;
}
}
public class 扑克牌
{
public static void main(String[] args)
{
//生成52张扑克牌
String[] colors = {"黑桃","方块","梅花","红桃"};
String[] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
LinkedList pokers = new LinkedList();
for(int i=0;i < colors.length;i++)
{
for(int j=0;j<nums.length;j++)
{
pokers.add(new poker(colors[i],nums[j]));
}
}
//洗牌
LinkedList shuffledpokers = new LinkedList();
while(shuffledpokers.size()<pokers.size())
{
Random x = new Random();
poker poke = (poker) pokers.get(x.nextInt(pokers.size()));
if(!shuffledpokers.contains(poke))
{
shuffledpokers.add(poke);
}
}
System.out.println("洗牌前:"+pokers);
System.out.println("洗牌后:"+shuffledpokers);
}
}
三、截图
再次运行: