假设items
数组由以下项目组成{3.1, 3.1, 3.1, 3.2, 3.2, 3.3, 3.4, 3.4, 3.4, 3.4, 3.1, 3.1}
我想要的是计算连续项目中每个项目的出现,例如:
3.1 = 3
3.2 = 2
3.3 = 1
3.4 = 4
3.1 = 2
我写了以下函数:
private void displayItems(List<Double> items) {
double current_item=0;
for(int i=0; i<items.size(); i++) {
int count=1;
current_item = items.get(i);
if(i != items.size()) {
for(int j=i+1; j<items.size(); j++) {
double next_item = items.get(j);
if(current_item == next_item) {
count++;
}else {
break;
}
}
System.out.println("item value is " + current_item + " and count is " + count);
}
}
}
我得到以下结果:
item value is 3.1 and count is 3
item value is 3.1 and count is 2
item value is 3.1 and count is 1
item value is 3.2 and count is 2
item value is 3.2 and count is 1
item value is 3.3 and count is 1
item value is 3.4 and count is 4
item value is 3.4 and count is 3
item value is 3.4 and count is 2
item value is 3.4 and count is 1
item value is 3.1 and count is 2
item value is 3.1 and count is 1
我该怎么做才能显示如下结果:
item value is 3.1 and count is 3
item value is 3.2 and count is 2
item value is 3.3 and count is 1
item value is 3.4 and count is 4
item value is 3.1 and count is 2
请不要说我不想统计整个数组中每个项目的出现,我只想统计其在连续项目中的出现。
最佳答案
您的代码正在迭代先前迭代中已经计算过的值。逻辑上的小调整可以按预期进行。
private void displayItems(List<Double> items) {
double current_item=0;
for(int i=0; i<items.size(); i++) {
int count=1;
current_item = items.get(i);
if(i != items.size()) {
int j=i+1;
for(; j<items.size(); j++) {
double next_item = items.get(j);
if(current_item == next_item) {
count++;
}else {
break;
}
}
System.out.println("item value is " + current_item + " and count is " + count);
i = j-1;
}
}
}
关于java - 计算数组中连续项的出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49635017/