Java-检查整数列表中的x个相似整数
我想浏览一个整数列表,如果我发现6个相似的整数,或者如果有5个相似的整数,或者如果有4个相似的整数,我会采取行动……我该怎么做呢。我的方法是:Java-检查整数列表中的x个相似整数,java,arrays,for-loop,if-statement,integer,Java,Arrays,For Loop,If Statement,Integer,我想浏览一个整数列表,如果我发现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 } public int-calculatePoints(
public int calculatePoints(ArrayList<Integer> dice) {
//Check for 6 alike
//if not, check for 5 alike
//if not, check for 4 alike
}
public int-calculatePoints(数组列表骰子){
//检查是否有6个相同
//如果没有,请检查是否有5个
//如果没有,请检查是否有4个相同
}
这里有一种方法:(假设您只想检查出现次数最多的数字)
公共静态整数计算点(ArrayList骰子){
int max=0;
用于(整数骰子:骰子){
int temp=收集频率(骰子、骰子);
如果(温度>最大值){
最大值=温度;
}
}
如果(最大值>=6){
//做事
}否则,如果(最大值>=5){
//做事
}否则如果(最大值>=4){
//做事
}
返回0;
}
基本逻辑:
-检查数组中的每个
整数
,并使用该方法查看它发生了多少次。如果大于最大值,则将数字解析为max
。然后在最后,它使用if-else
语句检查数字出现的次数,并在if
语句中执行所需操作 因为我没有足够的声誉编辑我的帖子,下面是我的答案@GBlodgett:
嘿!谢谢你的回复。我正在制作一个法克尔游戏,因此我需要找出列表中有多少个1、2、3、4、5和6,然后根据规则打分。我编写了一个似乎有效的代码,尽管必须有更有效的方法。请随意查看并给我一些反馈:
公共整数计算点(ArrayList骰子){
int点=0;
Map numodice=newhashmap();
numOfDice.put(1,0);
numOfDice.put(2,0);
掷骰子(3,0);
numOfDice.put(4,0);
掷骰子(5,0);
掷骰子(6,0);
for(整数编号:骰子){
if(numodice.get(num)==null){
numOfDice.put(num,1);
}
否则{
numOfDice.put(num,numOfDice.get(num)+1);
}
}
对于(int i=1;i你尝试过什么?你具体坚持了什么?到目前为止你尝试过什么?我想不出解决这个问题的方法。list参数可以有任意数量的元素,我不知道如何运行它来检查是否有x个相同的整数。我想在所有元素中添加一个for循环参数列表中的nts:for(Integer num:dice){}可以创建一个映射,因为这是为了检查列表中有多少类似的骰子。映射为Map感谢您的回复!请查看我发布的答案
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;
}
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;