简体   繁体   中英

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. Why is that?

ArryList.contains() checks if a particular object is present in the collection. You probably want to use the containsAll method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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