Reputation: 53
I have two arrays, need[ ] and bought[ ]. 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. 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].
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];
Upvotes: 2
Views: 584
Reputation: 393781
Your while
loop causes the infinite loop. 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(" ");
Upvotes: 5