我要算每个出现String
在ArrayList
包括字符串和整数。现在,我必须忽略与int
每个项目的数量相对应的变量,而只计算该列表中每个String的重复次数。
我的问题是,在课堂上我们只使用int做到了这一点。现在使用Strings时,我遇到了一个问题,因为“ abc”与“ Abc”不同,并且“ def of Ghi”与“ def of ghi”不同。
现在我拥有的代码是这样的:
Map<String, Integer> getCount1 = new HashMap<>();
{
for (ItemsList i : list) {
Integer count = getCount1.get(i.name);
if (count == null) {
count = 0;
}
getCount1.put(i.name, (count.intValue() + 1));
}
for (Map.Entry<String, Integer> entry : getCount1.entrySet())
f.println(entry.getKey() + " : " + entry.getValue());
}
但是正如我说的那样:它并没有正确地统计事件的发生。例如,我的列表中有一个出现,称为“ abc的Abc”,然后在input.txt文件列表中,我出现了4次相同的出现-“ abc的Abc”;“ Abc的abc”;“ Abc of Abc”和“ abc Of abc”-都用不同的方式书写,并且分别对它们进行计数,而不是对同一事件进行4次计数。
早期,我可以使用总计和平均值,equalsIgnoreCase()
因此可以在其中使用,因此无论大小写如何,它都将它们计入正确的列表中,而不是一次多次出现。
有没有一种方法我可以使用忽略大小写或将所有内容都转换为相同的大小写?
只是更新:而不是在.toLowerCase()
那里尝试,而是在FileReader
读取.txt文件并有效时使用了它i.name = name.toLowerCase();
谢谢您的宝贵时间,无论如何都需要帮助
.toLowerCase()
我没有尝试在那里,而是FileReader
在它读取.txt文件并使用时使用了它i.name = name.toLowerCase();
所以最后我的代码是这样的:
static void readFile(ArrayList<Items> list) throws IOException {
BufferedReader in = new BufferedReader(
new FileReader("input.txt")
);
String text;
while( (text = in.readLine()) != null ) {
if(text.length()==0) break;
Scanner line = new Scanner(text);
linha.useDelimiter("\\s*:\\s*");
String name = line.next();
int qtt = line.nextInt();
Items i = new Items();
i.name = name.toLowerCase();
i.qtt = qtt;
list.add(i);
}
in.close();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句