OthK :
I tried to count occurences of an object in a list, but looks like it's not working.
here is my class Card :
public class Card {
private int value;
private String type;
private String color;
}
and here, i'm trying to set up a deck of 104 cards, containing 2 occurences of each card, but looks like my condition isn't correct :
public static List<Card> InitializeDeck(){
for(int i=0;i<104;i++){
boolean isOk = true;
while (isOk){
int col = (int) (Math.floor(Math.random() * 2) + 1);
if (col == 1) {
color = "Black";
} else {
color = "Red";
}
value = (int) (Math.floor(Math.random() * 14));
while (value == 0) {
value = (int) (Math.floor(Math.random() * 14));
}
int ty = (int) (Math.floor(Math.random() * 4));
switch (ty) {
case 0:
type = "Spade";
break;
case 1:
type = "Heart";
break;
case 2:
type = "Diamond";
break;
case 3:
type = "Club";
break;
}
Card card = new Card(value, type, color);
if(deck.isEmpty() || deck.stream().filter(line -> card.equals(line)).count()<=1){
deck.add(card);
isOk=false;
}
}
}
return deck;
}
I get a deck of 104 cards, but with sometimes 4 occurences of the same card, or even not a single occurence, any tips ?
Thomas :
I'll summarize the comments on your question a little and give a brief example of how you'd build the deck without random numbers and with using enums.
First we define the enums:
enum Color {
RED,
BLACK;
}
enum CardType {
SPADE, //as per Yassin's comments you'll probably want to define the type's color later on
HEART, //you'd then use HEART(Color.RED) etc. - and provide the correct constructor
DIAMOND,
CLUB;
}
And the Card
class:
class Card {
private final int value;
private final CardType type;
private final Color color;
//I'll omit the constructor, getters, equals and hashcode for simplicity, they should be straight forward
}
And building the deck:
List<Card> deck = new ArrayList<>(208); //we're telling the list that we expect 208 elements
//build two cards for each combination and add them to the deck
for( int value = 1; value <= 14; value++ ) {
for( CardType type : CardType.values() ) {
for( Color color : Color.values() ) {
deck.add( new Card( value, type, color ) );
deck.add( new Card( value, type, color ) );
}
}
}
//shuffle the deck
Collections.shuffle( deck );