gpt4 book ai didi

java - 计算数组中连续项的出现次数

转载 作者:行者123 更新时间:2023-12-03 01:28:02 25 4
gpt4 key购买 nike

假设 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com