英文:
How to count the amount of times a string appears in csv file?
问题
我想要统计在CSV文件中特定单词出现的次数,但我的代码不起作用,不幸的是,由于某种原因,我的调试在eclipse中无法工作,所以很难确定发生了什么。我可能走错了方向,但如果有人有经验,我会感激任何人的建议。这是我一直在尝试让它工作的方式。
FileReader po = new FileReader("filename");
Scanner underinvscan = new Scanner(po);
for (int i = 0; i < file.size(); i++) {
String string = file.get(i).LOC;
if (!(string.contains("Under investigation"))) {
int count = 0;
count++;
System.out.println("there have been" + count + "under investigations");
}
}
英文:
I want to count the amount of times a certain word comes up in a CSV file, my code isnt working and unfortunately for some reason my debug wont work in eclipse so its hard to tell whats happening. I'm probably going about this wrong but if anyone has experience I would appreciate anyones input. this is how ive been trying to get it to work.
FileReader po = new FileReader("filename");
Scanner underinvscan = new Scanner(po);
for (int i = 0; i < file.size(); i++) {
String string = file.get(i).LOC;
if (!(string.contains("Under investigation"))) {
int count = 0; count++;
System.out.println("there have been" + count + "under investigations");
}
}
}
}
答案1
得分: 3
你需要将计数器移到循环外部,这样它就不会在每次循环中被重置:
int count = 0;
for (int i = 0; i < file.size(); i++) {
String string = file.get(i).LOC;
if (!(string.contains("Under investigation"))) {
count++;
}
}
System.out.println("已经有" + count + "个调查进行中");
而且可能需要更改条件吗?如果你想要计算包含 "Under investigation" 的字符串,你需要从条件中删除 `!`,目前你正在计算不包含 "Under investigation" 的字符串。
<details>
<summary>英文:</summary>
You need to move the counter outside of the loop, so it is not reset in every loop:
int count = 0;
for (int i = 0; i < file.size(); i++) {
String string = file.get(i).LOC;
if (!(string.contains("Under investigation"))) {
count++;
}
}
System.out.println("there have been" + count + "under investigations");
And possible the condition? If you want to count the strings that contain the "Under investigation" you need to remove the `!` from the condition, currently you are counting the strings that do not contain the "Under investigation".
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论