有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

假设我有一个食物对象列表。我的程序在读取文件时不会捕获重复的字符串,我也不确定原因。如果字符串“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); 
            }
        }
    }

共 (0) 个答案