我正在尝试使用 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/