如果我找到6个相似的整数,或者如果有5个相似的整数,或者如果有4个相似的其他等等,我想通过整数列表并采取行动......我怎么能做这个。我有方法:
public int calculatePoints(ArrayList<Integer> dice) {
//Check for 6 alike
//if not, check for 5 alike
//if not, check for 4 alike
}
答案 0 :(得分:0)
Here is a way to do it: (Assuming you only want to check against the number that occurs the most)
public static int calculatePoints(ArrayList<Integer> dice) {
int max = 0;
for(Integer die : dice) {
int temp = Collections.frequency(dice, die);
if(temp > max) {
max = temp;
}
}
if(max >= 6) {
//Do stuff
} else if (max >=5) {
//Do stuff
} else if (max >= 4) {
//Do stuff
}
return 0;
}
Basic logic:
-Go through every Integer
in the array and use the frequency method to see how many times it occurred. If it is more than the max, then resolve the number to max
. Then at the end, it if-else
statements to check how many times the number occurred and do what you want inside the if
statement.
答案 1 :(得分:0)
由于我没有足够的声誉来编辑我的帖子,这是我的答案@GBlodgett:
喂!谢谢回复。我正在制作一个Farkle游戏,因此我需要找出列表中有多少1s,2s,3s,4s,5s和6s然后给出积分(遵循规则)。我制作了一个似乎有效的代码,尽管必须有一个更有效的方法来实现它。请随意查看并给我一些反馈:
public int calculatePoints(ArrayList dice){
int points = 0;
Map<Integer,Integer> numOfDice = new HashMap<Integer,Integer>();
numOfDice.put(1, 0);
numOfDice.put(2, 0);
numOfDice.put(3, 0);
numOfDice.put(4, 0);
numOfDice.put(5, 0);
numOfDice.put(6, 0);
for(Integer num : dice) {
if(numOfDice.get(num) == null) {
numOfDice.put(num, 1);
}
else {
numOfDice.put(num, numOfDice.get(num)+1);
}
}
for(int i=1; i <= numOfDice.size(); i++) {
if(i == 1) {
if(numOfDice.get(1) < 3) {
points += numOfDice.get(1)*100;
}
else if(numOfDice.get(1) == 3) {
points += 1000;
}
else if(numOfDice.get(1) == 4) {
points += 2000;
}
else if(numOfDice.get(1) == 5) {
points += 3000;
}
else if(numOfDice.get(1) == 6) {
points += 5000;
}
}
else {
if(i == 5) {
if(numOfDice.get(5) < 3) {
points += 50*numOfDice.get(5);
continue;
}
}
//All else
if(numOfDice.get(i) == 3) {
points += 100*i;
}
else if(numOfDice.get(i) == 4) {
points += 200*i;
}
else if(numOfDice.get(i) == 5) {
points += 300*i;
}
else if(numOfDice.get(i) == 6) {
points += 400*i;
}
}
}
return points;
}