java - 如何检查 ArrayList 中的单词是否是文件中名称的子字符串,然后增加该单词的计数?
问题描述
因此,如果我试图读取一个配方文件,该文件应该找到与我的 ArrayList 上的单词匹配的单词,如果匹配,该单词的计数就会增加。这是我到目前为止所拥有的,但我被困在我应该在循环中做什么。
public class Main {
private Scanner inp = new Scanner( System.in);
private ArrayList<String> foodList = new ArrayList<String>();
private int ingredientCount = 0;
public A1() {
foodList.add("baking powder");
foodList.add("baking soda");
foodList.add("cheese");
foodList.add("broth");
foodList.add("tomato paste");
foodList.add("tomato");
foodList.add("flour");
foodList.add("egg");
foodList.add("garlic");
foodList.add("cheese");
foodList.add("rice");
foodList.add("onion");
foodList.add("salt");
foodList.add("pepper");
foodList.add("vinegar");
foodList.add("carrot");
foodList.add("sweet potato");
foodList.add("potato");
foodList.add("cream");
foodList.add("milk");
foodList.add("bean");
foodList.add("green bean");
foodList.add("beef");
foodList.add("chicken");
foodList.add("cumin");
foodList.add("basil");
foodList.add("oregano");
foodList.add("oil");
foodList.add("fish");
}
private void readFile() {
while (inp.hasNext()) {
String nextLine = inp.next().toLowerCase();
if (nextLine.contains(foodList())) {
totalwordcount++; //This is the part I'm stuck on. How do I only
//incriment that food item from the list?
}
}
}
}
解决方案
如果您不允许使用 aMap<String, Integer>
来保留计数,则可以只使用数组:
private Scanner inp = new Scanner( System.in);
private ArrayList<String> foodList = new ArrayList<String>();
private int[] ingredientCount;
public A1() {
foodList.add("baking powder");
foodList.add("baking soda");
// ...
foodList.add("oil");
foodList.add("fish");
ingredientCount = new int[foodList.size()];
}
private void readFile() {
while (inp.hasNext()) {
String nextLine = inp.next().toLowerCase();
for(int i=0; i<foodList.size(); i++)
{
if (nextLine.contains(foodList.get(i))) {
ingredientCount[i] += 1;
}
}
}
for(int i=0; i<foodList.size(); i++)
{
System.out.printf("%s occured %d time(s)\n", foodList.get(i), ingredientCount[i]);
}
}
推荐阅读
- reactjs - 如何解决使用 this.refs 已被弃用?
- r - 按值范围对数据框进行子集
- node.js - 在 node.js 项目中安装 NuGet 包
- php - WooCommerce 产品变体:自动启用管理库存并设置库存数量
- excel - 在 vb.net 中创建 excel 对象的最佳方法
- rest - 邮递员响应正文中的电子邮件 ID 转换为小写字母
- sql - 解释 Select max without Groupby
- r - R - 日期 ddmmyyyy 和 dd/mm/yyyy 在同一列
- python - Python子进程不同的方法
- elasticsearch - 弹性查询每天按指定时间范围聚合