java - 计算字符串数组中出现的次数

标签 java arrays

我正在尝试使用 Java 数组。我想要做的是计算数组字符串元素的出现次数。例如:

Clubs - 8 
Clubs - Ace 
Clubs - Jack
Hearts - 9 
Spades - 3
Hearts - 6

出现次数:

Clubs - 3
Hearts - 2
Spades - 1
Diamonds - 0

到目前为止我只编写了这个:

public class CardGame {
public static void main(String[] args){

     String[] suit = { "Clubs", "Hearts", "Diamonds", "Spades" };
     String[] deck = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
                        "Jack", "Queen", "King", "Aces" };

     for( int a = 0; a < 7; a++ ){
     int i = (int) ( Math.random() * suit.length );
     int j = (int) ( Math.random() * deck.length );
         //System.out.println( "Suit " + suit[i] + " Deck " + deck[j] );
     System.out.println( suit[(int) (Math.random() * suit.length)]
             + " : " + deck[(int) (Math.random() * deck.length)]);
     }
            System.out.println();

  }
}

给我一​​些关于如何实现这一目标的想法。谢谢。

注意:这不是作业。我只是想给自己做一些关于数组的练习。

最佳答案

我相信您误解了上一个问题的答案。这个想法是在循环中使用 i 和 j 的值,而不是生成它们两次。这是一个工作示例。我没有使用 HashMap ,因为您事先知道花色及其数量,因此只需一个数组就足够了:

public class Main {
    public static void main(String[] args){

         String[] suit = { "Clubs", "Hearts", "Diamonds", "Spades" };
         String[] deck = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
                            "Jack", "Queen", "King", "Aces" };
         int counts[] = new int[4];
         for( int a = 0; a < 7; a++ ){
         int i = (int) ( Math.random() * suit.length );
         int j = (int) ( Math.random() * deck.length );
             //System.out.println( "Suit " + suit[i] + " Deck " + deck[j] );
         System.out.println( suit[i] + " : " + deck[j]);
         counts[i]++;
         }
                System.out.println();
         for (int i =0;i<4;++i){
            System.out.println(suit[i] + " : " + counts[i]);
         }

      }
    }

您可以在 ideone 上看到代码.

关于java - 计算字符串数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12796419/

相关文章:

arrays - 检查两个数组是否相等的算法

php - 遍历多维数组

c - 如何在 C 中使用数组

java - 未从 Account 类获取最新版本的 stripe 中的 stripePublishableKey

java - 装饰器模式是否对具有许多字段的 "bulky"类有不利影响?

java - 我将如何对此 JSON 解析执行 Angular JS ng-repeat ?

java - 接收派生自抽象类的对象作为方法中的参数

java - AspectJ 指示符 @args() 在 Spring AOP 中不起作用

ios - Swift 问题 - 数组列表中包含二维数组的字典

php - 只是在 mysql 错误中插入空白数组()