Java生成52张纸牌,模拟洗牌,并将洗牌结果打印出来,每次询问是否取出一张纸牌,直至所有纸牌被取出

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		ArrayList arrayList = new ArrayList();
		makeCards(arrayList);
		print(arrayList);
		fixCards(arrayList);
		print(arrayList);

		while (!arrayList.isEmpty()) {
			Scanner input = new Scanner(System.in);
			System.out.print("是否取出一张纸牌:Y or N : ");

			String s = input.nextLine();
			if (s.equalsIgnoreCase("Y")) {
				getCard(arrayList);
			}

		}
		System.out.println("所有纸牌已取出!");
	}

	// 定义纸牌
	public static void makeCards(ArrayList arrayList) {
		String colors[] = { "红桃", "方块", "黑桃", "梅花" };
		for (int i = 0; i < colors.length; i++) {
			for (int j = 1; j < 14; j++) {
				String a = changes(j);
				arrayList.add(new Card(colors[i], a));

			}
		}
	}

	// 数字与字符的转换
	public static String changes(int num) {
		String b;
		switch (num) {
		case 1:
			b = "A";
			break;
		case 11:
			b = "J";
			break;
		case 12:
			b = "Q";
			break;
		case 13:
			b = "K";
			break;
		default:
			b = String.valueOf(num);
		}
		return b;
	}

	// 打印纸牌
	public static void print(ArrayList arrayList) {
		for (int i = 0; i < arrayList.size(); i++) {
			arrayList.get(i).print();
		}
	}

	// 打乱纸牌
	public static void fixCards(ArrayList arrayList) {
		Random i = new Random();
		int k;
		for (int j = 0; j < arrayList.size(); j++) {
			k = i.nextInt(52);
			arrayList.add(j, arrayList.remove(k));
		}
	}

	// 取一张纸牌
	public static void getCard(ArrayList arrayList) {
		int j = arrayList.size() - 1;
		arrayList.get(j).print();
		arrayList.remove(j);
	}
}




import java.util.Random;
import java.util.Stack;

public class Card {
	String color;
	String num;
	
	public Card(String color,String num) {
		this.color=color;
		this.num=num;
	}
	public void print() {
		System.out.println(color+num);
	}
}

你可能感兴趣的:(java编程)