首页 > 解决方案 > 如何检查 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?
            }
        }
    }  
}

标签: javaarraylist

解决方案


如果您不允许使用 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]);
  }
}  

推荐阅读