程序未捕获重复的字符串和正确处理的问题

时间:2018-09-28 04:00:53

标签: java oop arraylist

假设我有一个食物对象foodList的ArrayList。当我读取文件时,我的程序没有捕获重复的字符串,我不确定为什么。如果字符串“ oil”在文件中出现两次,我的程序将创建一个新对象,当我不想这样做时,因为它在读取第一个字符串“ oil”后应该存在于ArrayList中

while(recipeFile.hasNext())
    {
        String ingredient = recipeFile.nextLine();
        //System.out.println("line " +ingredient );
        ingredient = ingredient.toLowerCase().trim();
        if (ingredient.equals("---")) 
        {
            isIngredient = !isIngredient;
        }
        else if (isIngredient) 
        {
            boolean found = false;
            for(int i = 0; i<foodList.size(); i++)
            {
                Food food2Compare = foodList.get(i);
                //System.out.println("comparing " + food1.getFoodName() +" and " +ingredient );
                int currentFreq = food2Compare.getFrequency();
                if(food2Compare.getFoodName().contains(ingredient) &&!found)
                {
                    food2Compare.setFrequency(currentFreq+1);
                    found = true;
                }
            }

            if (found == false)
            {
                ingredient = ingredient.substring(ingredient.lastIndexOf(" ")+1);
                if(ingredient.substring(ingredient.length() - 1).equals("s"))
                {
                    ingredient = ingredient.substring(0, ingredient.length() - 1);
                }
                else if(ingredient.substring(ingredient.length() - 2, ingredient.length() - 1).equals("es"))
                {
                    ingredient = ingredient.substring(0, ingredient.length() - 3);
                }
                System.out.println("line " +ingredient );
                foodList.add(new Food(ingredient, 1));
                Collections.sort(foodList); 
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

food2Compare.getFoodName().contains(ingredient)替换为ingredient.contains(food2Compare.getFoodName())