如何检查布尔数组中是否存在任何 true 实例,然后从相应的数组中打印这些实例?

How to check a boolean array for any instances of true and then print those instances from a corresponding array?

我有两个数组,need[ ] 和 bought[ ]。 need[ ] 是一个字符串数组,包含 7 个不同的项目,根据布尔 bought[] 数组的相应索引值,这些项目被认为是 bought(true) 或 need(false)。我想在实际购买商品时 打印已购买商品的列表。但是,我目前的技术是在 need[1].

处生成项目的无限循环
public static void listSupplies(String[] need, boolean[] bought){
        /*Line of code in the while loop checks the whole array for an instance of 'true'*/
        if(areAllFalse(bought) == true){
            System.out.println("Inventory:");
            for (int i = 0; i < need.length; i++) { 
                if(bought[i] == true){
                    System.out.print(need[i] + " "); System.out.println(" "); break;
                }
            }
            System.out.println("");
        }
        System.out.println("Need:");
        for (int i = 0; i < need.length; i++) { 
            while(bought[i] == false){
                System.out.print(need[i] + " "); System.out.println(" ");
            }
        }
        System.out.println("");
        mainMenu();
    }
    //Checks to see if the array contains 'true'
    public static boolean areAllFalse(boolean[] array){
        for(boolean val : array){
            if(val) 
                return true;
        } 
        return false;
    }

(在此代码之前,数组是这样声明的:)

String[] needInit = {"Broom", "School robes", "Wand", "The Standard Book of Spells", "A History of Magic", "Magical Drafts and Potions", "Cauldron"};
boolean bought[] = new boolean[7];

您的 while 循环导致无限循环。你不需要它。如果您只想打印购买的物品:

变化:

    for (int i = 0; i < need.length; i++) { 
        while(bought[i] == false){ // here's the cause of the infinite loop
            System.out.print(need[i] + " "); System.out.println(" ");
        }
    }

收件人:

    for (int i = 0; i < need.length; i++) { 
        if (bought[i]){
            System.out.print(need[i] + " "); 
        }
    }
    System.out.println(" ");