JAVA练习——纸牌,有发牌和洗牌功能

牌的创建和存放

如题,实现纸牌功能,需要先有一副牌,所以我用for和switch嵌套得到一副牌,再用Array存放纸牌

package com;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Test {
//o用来表示第几张牌
	private static int o;

List list = new ArrayList();
		String name = "";
		for (int i = 1; i <= 13; i++) {
			switch (i) {
			//输入除了正常数字外的,A,J,Q,K
			case 1:
				name = "A";
				break;
			case 11:
				name = "J";
				break;
			case 12:
				name = "Q";
				break;
			case 13:
				name = "K";
				break;
			default:
			//加空字符串转换为字符串类型
				name = "" + i;
			}
			//为纸牌附上花色
			list.add("♥" + name);
			list.add("♠" + name);
			list.add("♦" + name);
			list.add("♣" + name);
		}
		//输出纸牌
		System.out.print(list);
		System.out.println();
        //调用洗牌功能
		shuffle(list);
	}

洗牌

	public static void shuffle(List list) {
		Scanner scanner = new Scanner(System.in);
		//询问玩家是否需要洗牌
		System.out.println("是否洗牌?(y/n)");
		//若为y则洗牌
		if ("y".equals(scanner.nextLine())) {
		//调用Collections类里的shuffle方法打乱牌序
			Collections.shuffle(list);
			System.out.print(list);
			System.out.println();
			//调用发牌功能
			deal(list);
		}
	}

发牌

public static void deal(List list) {
		Scanner scanner = new Scanner(System.in);
		//友好提示用户是否需要发牌
		System.out.println( "发牌?(y/n)");
		if ("y".equals(scanner.nextLine())) {
		//输出第一张牌
			System.out.println(list.get(o));
		//输出后,牌序+1
			o++;
		//友好提示当前是第几张牌
			System.out.println(o);
			//发牌后调用自己,实现多次发牌
			deal(list);
		} else {
			shuffle(list);
		}
	}

}

你可能感兴趣的:(Java)