[英]How to find the number of times a specific element occurs in an Array list in Java
I have written a method with the aim to count the number of times a specific flavour of crisps appears in a snack machine in blueJ 我写了一种方法,目的是计算特定口味的薯片在blueJ小吃机中出现的次数
public int countPacks(String flavour){
int n = 0;
int nrFlavour = 0;
while( n < packets.size()) {
if( packets.get(n).equals(flavour)){
nrFlavour++;
n++;
}
else n++;
}
return nrFlavour;
}
I have an Arraylist 'packets' which holds PackOfCrisps objects which have a specific flavour. 我有一个Arraylist'packets',其中包含具有特定风味的PackOfCrisps对象。 However when I have added say three packets of "salt" flavour crisps and I run this method, inputting "salt" as the flavour, it just returns 0 as though there are no PackOfCrisps objects with flavour "salt".
但是,当我添加了说三个数据包的“盐”风味薯片并运行此方法时,输入“ salt”作为风味剂,它只会返回0,就好像没有带有“盐”风味的PackOfCrisps对象一样。 Sorry if this doesn't make sense.
抱歉,如果这没有意义。 I am very new to Java and I have tried to explain my problem the best I can.
我对Java还是很陌生,我已经尽力解释了我的问题。 :)
:)
The list packets
holds PackOfCrisps
objects, and the method takes a String
parameter. 列表
packets
包含PackOfCrisps
对象,并且该方法采用String
参数。 So the statement packets.get(n).equals(flavour)
is comparing a PackOfCrisps
object to a String
, hence the count variable will never increase. 因此,语句
packets.get(n).equals(flavour)
将PackOfCrisps
对象与String
进行比较,因此count变量将永远不会增加。
You need to compare the flavour
string to the specific field of the object, something like: 您需要将
flavour
字符串与对象的特定字段进行比较,例如:
if(packets.get(n).getFlavour().equals(flavour)){
On a side note, you can replace the while
loop with a simple for
loop and remove the increment of n
. 附带一提,您可以使用简单的
for
循环替换while
循环,并删除n
的增量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.