简体   繁体   English

为什么 boolean 值不注册为真?

[英]Why doesn't the boolean value register as true?

I am creating a shopping list program where it will ask the user for a list of input of pantry items.我正在创建一个购物清单程序,它将要求用户输入食品储藏室物品的清单。 After that, the computer will compare the user's input and a pre-determined list of pantry items to see if the user got everything needed.之后,计算机会将用户的输入与预先确定的食品储藏室物品清单进行比较,以查看用户是否得到了所需的一切。 Finally, it will either print out "You got everything," or "you still need something" plus the item missing.最后,它会打印出“你得到了一切”或“你还需要一些东西”加上缺少的东西。

This is the code I have, and everything works just fine, except one tiny error.这是我的代码,除了一个小错误外,一切正常。

import java.util.*;

public class TheList
{
    public static void main(String args[])
    {
        //scanner for user input
        Scanner scan = new Scanner(System.in);
        
        //pantry
        ArrayList<String> pantry = new ArrayList<String>();
        pantry.add("Bread");
        pantry.add("Peanut Butter");
        pantry.add("Chips");
        pantry.add("Jelly");
        
        //user input
        ArrayList<String> input = new ArrayList<String>();
        while(true)
        {
            System.out.println("Please enter an ingredient ('done' when complete): ");
            String userInput = "";
            if (scan.hasNextLine())
            {
                userInput = scan.nextLine();
            }
            if (userInput.equals("done"))
            {
                break;
            }
            input.add(userInput);

        }
        
        //print out result
        boolean shoppingDone = input.contains(pantry);
        if (shoppingDone == true) {
            System.out.println("It looks like you have everything to make your recipe!");
        }
        else {
            pantry.removeAll(input);
            System.out.println("You need to go shopping!");
            System.out.println("The following ingredients are missing:");
            System.out.println(pantry);
        }
    }
}

My boolean value doesn't register as true, even if all elements from pantry list is contained in the input list.我的 boolean 值未注册为 true,即使 pantry 列表中的所有元素都包含在输入列表中。 Why is that?这是为什么?

ArryList.contains() checks if a particular object is present in the collection. ArryList.contains()检查集合中是否存在特定的 object。 You probably want to use the containsAll method.您可能想要使用containsAll方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM