简体   繁体   English

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

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

I have two arrays, need[ ] and bought[ ]. 我有两个数组,need []和buy []。 need[ ] is a String array containing 7 different items that are considered bought(true) or need(false) according to the corresponding index value of the boolean bought[] array. need []是一个String数组,其中包含7个不同的项目,根据布尔型buy []数组的相应索引值,这些项目被视为buy(true)或need(false)。 I want to print a list of the bought items only when items have actually been bought. 我想打印, 只有当项目实际上已经买下了购买的物品清单。 However, my current technique is producing an infinite loop of the item at need[1]. 但是,我目前的技术是根据需要生成一个无限循环的项目[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;
    }

(Before this code, the arrays were declared as such:) (在此代码之前,数组是这样声明的:)

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];

Your while loop causes the infinite loop. 您的while循环会导致无限循环。 You don't need it. 不用了 If you only want to print the bought items : 如果您只想打印购买的物品:

Change : 变更:

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

To : 至 :

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

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

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