我已经分配了一个带阵列的程序来构建一副牌,我需要一个程序来改变牌组。我不知道从哪里开始。我考虑过创建一个名为shuffleDeck的新方法,但我不确定它是否可以正常使用这两个数组。对于我来说,数组通常是一个新的主题,当有两个阵列构建每个单独的卡时,我不确定如何改组牌组。
请不要直接回答,但我们将非常感谢您提供的一些提示/帮助。
编辑:我尝试使用Collections.shuffle,似乎它没有使用Strings正确构建。
import java.util.*;
import java.io.*;
public class cards_st {
public static void main(String[] args) {
String [] card = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
String [] suit = {" of hearts"," of clubs"," of spades", " of diamonds"};
String [] odeck = new String[52];
buildDeck(odeck,card,suit);
for(int d = 0; d <52; d++)
System.out.println(odeck[d]);
}
public static void buildDeck(String [] tdeck,String [] tcard, String [] tsuit)
{
int count = 0;
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 4; j++)
{
tdeck[count]= tcard[i] + tsuit[j];
count++;
}
}
}
}
答案 0 :(得分:0)
如果我能提出建议,那么如果你遵循oop会更好。你拥有一个主要课程。你正在使用字符串&#34;常量&#34;这不安全。将正确的元素封装到对象中:卡片和卡片。下一张卡片将有卡片(1,2,3,4,5)和套件(心脏,......)。类Deck将具有一组Card对象和方法,通过遍历所有枚举的值和创建卡来初始化。接下来使用collections.shuffle来改变它。
public class Card {
public enum CardType {
ONE,
TWO,
THREE;
}
public enum Suit {
HEARTS,
CLUBS,
}
private CardType cardType;
private Suit suit;
constructor && getters (...)
}
public class Deck {
List<Card> cards = new ArrayList<Card>();
public void init() {
for(CardType cardType : CardType.values()) {
for(Suit suit : Suit.values()) {
cards.add(new Card(cardType, suit));
}
}
Collections.shuffle(cards);
}
}
您还可以为枚举类型
指定字符串名称public enum Suit {
HEARTS("of hearts");
private String toString;
public Suit(String toString) {
this.toString = toString;
}
@Override
public String toString() {
return toString;
}
}
答案 1 :(得分:0)
String [] cards = {"H2","H3","H4","H5","H6","H7","H8","H9","H10","HJack","HQueen","HKing","HAce"
,"D2","D3","D4","D5","D6","D7","D8","D9","D10","DJack","DQueen","DKing","DAce"
,"C2","C3","C4","C5","C6","C7","C8","C9","C10","CJack","CQueen","CKing","CAce"
,"S2","S3","S4","S5","S6","S7","S8","S9","S10","SJack","SQueen","SKing","SAce"
};
List<String> deck = Arrays.asList(cards);
System.out.println("Initial collection: "+deck);
// shuffle the list
Collections.shuffle(deck);
System.out.println("Final collection after shuffle: "+deck);