I’m experimenting with Java arrays. What I want to do is count the occurrences of an array string element. For example:
Clubs - 8
Clubs - Ace
Clubs - Jack
Hearts - 9
Spades - 3
Hearts - 6
Number of occurrences:
Clubs - 3
Hearts - 2
Spades - 1
Diamonds - 0
So far I only have coded this:
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();
}
}
Give me some ideas on how to accomplish this. Thanks.
NOTE: This is not a homework. I’m just trying to give myself some exercises regarding arrays.
I believe you have missunderstood the answer to your previous question. The idea is to use the values of i and j in the cycle, not to generate them twice. Here is a working example. I am not using hash map because you know the suits and their count aforehand so just an array is enough:
You can see the code on ideone.