问题描述
- C#中关于集合类的一个问题
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;namespace ConsoleApplication1
{
public class Cards
{
Hashtable htCards;
ArrayList randomList;
public Hashtable SetCards() //哈希表添加54张牌
{
htCards = new Hashtable(54, 1);
int i;
string card = "";
for (i = 1; i <= 13; i++)
{if (i <= 10) { card = "红桃" + i.ToString(); } else { switch (i) { case 11: card = "红桃J"; break; case 12: card = "红桃Q"; break; case 13: card = "红桃K"; break; } } htCards.Add(i, card); } for (i = 14; i <= 26; i++) { if (i <= 23) { card = "黑桃" + (i - 13).ToString(); } else { switch (i) { case 24: card = "黑桃J"; break; case 25: card = "黑桃Q"; break; case 26: card = "黑桃K"; break; } } htCards.Add(i, card); } for (i = 27; i <= 39; i++) { if (i <= 36) { card = "方片" + (i - 26).ToString(); } else { switch (i) { case 37: card = "方片J"; break; case 38: card = "方片Q"; break; case 39: card = "方片K"; break; } } htCards.Add(i, card); } for (i = 40; i <= 52; i++) { if (i <= 49) { card = "梅花" + (i - 39).ToString(); } else { switch (i) { case 50: card = "梅花J"; break; case 51: card = "梅花Q"; break; case 52: card = "梅花K"; break; } } htCards.Add(i, card); } htCards.Add(53, "小王"); htCards.Add(54, "大王"); return htCards; } public ArrayList SendCards() //发牌,生成13个不重复的随机数 { randomList = new ArrayList(); Random r = new Random(); for (int j = 0; j < 13; j++) { int index; index = r.Next(1, 54); htCards.Remove(index); while (!htCards.Contains (index)||randomList.Contains(index)) { index = r.Next(1, 54); } randomList.Add(index); } return randomList; } } class Program { static void Main(string[] args) { Cards cards = new Cards(); Hashtable hxCards = cards.SetCards(); int count = 0; for (int i = 0; i < 2; i++) { ArrayList indexList = cards.SendCards(); Console.WriteLine("第{0}位玩家的牌已发,如下:",i+1); foreach (int index in indexList) { if (count % 5 == 0) { Console.WriteLine(); } count++; Console.Write("{0}t", hxCards[index]); } Console.WriteLine(); } Console.ReadLine(); } }
解决方案
hxCards[index]有空白项,调试下。另外几行代码就能写好的代码,你能写这么多,佩服。
解决方案二:
如果你采纳了回答,我可以从头写一个给你。
时间: 2024-09-22 13:06:47