gpt4 book ai didi

java - 计算文件中每个字符的个数

转载 作者:行者123 更新时间:2023-11-29 04:45:59 24 4
gpt4 key购买 nike

我正在逐个字符地读取文本文件的内容,然后按升序对它们进行排序并计算每个字符出现的次数。当我运行程序时,我的数字偏离了方向,例如文件中有 7 个“A”,但我得到了 17。我认为这意味着我的计数有问题,或者我正在阅读的方式字符。有什么问题吗?

public class CharacterCounts {

public static void main(String[] args) throws IOException{
String fileName = args[0];
BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
ArrayList<Character> vals = new ArrayList<Character>();
ArrayList<Integer> valCounts = new ArrayList<Integer>();

while(in.read() != -1){
vals.add((char)in.read());
}

Collections.sort(vals);

//This counts how many times each char occures,
//resets count to 0 upon finding a new char.
int count = 0;
for(int i = 1; i < vals.size(); i++){
if(vals.get(i - 1) == vals.get(i)){
count++;
} else {
valCounts.add(count + 1);
count = 0;
}
}

//Removes duplicates from vals by moving from set then back to ArrayList
Set<Character> hs = new HashSet<Character>();
hs.addAll(vals);
vals.clear();
vals.addAll(hs);

//System.out.print(vals.size() + "," + valCounts.size());

for(int i = 0; i < vals.size(); i++){
//System.out.println(vals.get(i));
System.out.printf("'%c' %d\n", vals.get(i), valCounts.get(i));
}

}
}

最佳答案

当你写的时候

if(vals.get(i - 1) == vals.get(i)){

两者是完全不同的引用,它们根本不相等。你必须比较它们的值(value)。

你想要

if(vals.get(i - 1).equals(vals.get(i))){

关于java - 计算文件中每个字符的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170487/

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