我试图计算列表中某个对象的出现次数,但是看起来它不起作用。
这是我的班级证:
public class Card {
private int value;
private String type;
private String color;
}
在这里,我正在尝试设置104张卡片组,每张卡片包含2次出现,但看起来我的情况不正确:
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;
}
我得到104张纸牌,但是有时同一张纸出现4次,甚至没有一次出现任何提示吗?
答案 0 :(得分:5)
我将对您的问题进行一些总结,并给出一个简短的示例,说明如何构建不带随机数和使用枚举的套牌。
首先我们定义枚举:
function foo(){
console.log(this);
}
foo.call(foo); //foo function
foo.call(); //window object
还有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;
}
类:
Card
并构建甲板:
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
}