题目:将一副扑克牌(52张,不含大小王)初始化,然后洗牌。分别输出洗牌前后结果。
import java.util.Random;
public class example
{
public static void main(String[] args)
{
int[] cards=new int[52];//整形数组
int[] array;
String[] kinds={"黑","红","花","片"};//kind数组盛放的是花型
String[] nums={ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };//52张牌对应的数字
for(int i=0;i<cards.length;i++) // 一定要注意,这一定要写在方法内部,不能直接写在类里面。
{
cards[i]=i;
}
System.out.println("排序前");
show(cards,kinds,nums);
System.out.println("排序后(第一种方案)");
shuffle1(cards); // 方案1
show(cards,kinds,nums);
System.out.println("排序后(第二种方案)");
shuffle2(cards); // 方案2
show(cards,kinds,nums);
}
//输出52张牌
public static void show(int[] cards,String[] kinds,String[] nums)
{
for(int i=0;i<cards.length;i++)
{
int kind=cards[i]/13;//取商得花型
int num=cards[i]%13;//取余得数字
System.out.print(kinds[kind]+nums[num]+"\t");
if((i+1)%13==0)//每13张换一行输出
{
System.out.println();
}
}
}
//
public static void shuffle1(int[] cards)
{
Random rand=new Random();
int random, temp;
for(int i=0;i<cards.length;i++)
{
random=rand.nextInt(52);//0~51
if(cards[random]!=cards[i])
{
temp=cards[i];
cards[i]=cards[random]; // 这里注意一定是cards[random]!,两张牌的交换!!
cards[random]=temp;
}
}
//return cards;
}
public static void shuffle2(int[] cards)
{
Random rand=new Random();
for(int i=0;i<cards.length;i++)
{
cards[i]=rand.nextInt(52);
for(int j=0;j<i;j++)
{
if(cards[i]==cards[j])
{
cards[i]=rand.nextInt(52);
j=-1;//注意j的值
}
}
}
//return cards;
}
}