簡體   English   中英

為什么 boolean 值不注冊為真?

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

我正在創建一個購物清單程序,它將要求用戶輸入食品儲藏室物品的清單。 之后,計算機會將用戶的輸入與預先確定的食品儲藏室物品清單進行比較,以查看用戶是否得到了所需的一切。 最后,它會打印出“你得到了一切”或“你還需要一些東西”加上缺少的東西。

這是我的代碼,除了一個小錯誤外,一切正常。

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);
        }
    }
}

我的 boolean 值未注冊為 true,即使 pantry 列表中的所有元素都包含在輸入列表中。 這是為什么?

ArryList.contains()檢查集合中是否存在特定的 object。 您可能想要使用containsAll方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM