我必须:创建一个模拟一副牌的数组。例如,“1_of_diamonds”代表钻石的ace,“2_of_diamonds”代表2颗钻石,最多为“13_of_diamonds”,代表钻石之王。西装俱乐部,心脏和黑桃以类似的方式表示。所有这些元素都应该在一个数组中。应使用计数器控制的循环填充数组。将数组的内容输出到屏幕。洗牌。
我有代码来重新调整它的工作,但我不知道如何使用计数器控制循环填充数组。
//这是我的代码
import java.util.Random;
public class Cards{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
} //end main
public String[] shuffle(String[] deck) {
Random rnd = new Random();
for (int i = deck.length - 1; i >= 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
String a = deck[index];
deck[index] = deck[i];
deck[i] = a;
}
return deck;
}
}// end class
下面的填充方法可能有所帮助。
public static String[] populate(){
String[] cards=new String[52];
String[] types={"hearts", "spades", "clubs", "diamonds"};
int current = 0;
for(String type:types)
for(int i = 1; i <= 13 ; i++)
cards[current++] = i + "_of_" + type;
return cards;
}
有使用流的Java8 +方式和使用循环的旧方式。我假设你想要更老的方式,但我认为这两者都很有意思。
// Streams way
String[] array = Stream.of("spades", "diamonds", "hearts", "clubs")
.map(suit -> IntStream.rangeClosed(1, 13).mapToObj(value -> value + "_of_" + suit))
.flatMap(Function.identity())
.toArray(String[]::new);
// for loops way
String[] deck = new String[52];
for(int i = 0; i < 4; i++){
String suit;
switch(i){
case 0:
suit = "spades";
break;
case 1:
suit = "diamonds";
break;
case 2:
suit = "hearts";
break;
case 3:
default:
suit = "clubs";
break;
}
for(int value = 0; value < 13; value++){
deck[i * 13 + value] = (value + 1) + "_of_" + suit;
}
}
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(deck));