java - (Java)我不知道如何用所需的计数器控制循环填充数组

标签 java arrays loops random shuffle

我必须: 创建一个模拟一副纸牌的数组。例如,“1_of_diamonds”代表 A 钻石,“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;
}

关于java - (Java)我不知道如何用所需的计数器控制循环填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55859141/

相关文章:

java - 如何使用 GSON 检查 JSON 在 Java 中是否有效?

java - 在包含 1000 个元素的整数数组中查找多种众数

C编程: Sum of a sequence of integers until zero and prints the sum of two multiplied integers

精益编程语言中的循环

c - 正在重新分配的指针未在函数中分配 char* realloc

Javascript - 在循环中选择 "not this"

java - 现实世界从 Java 文件中读取

java - 如何在Java中存储ImageIcon

java - 在查询中映射复合外键

javascript - 如何收集选中的单选按钮并放入数组中然后发布到 Controller