Dun*_*ins 2 java arrays boolean infinite-loop
我有两个数组,需要[]并购买[].need []是一个String数组,包含根据boolean buying []数组的相应索引值被视为buy(true)或need(false)的7个不同项.我想打印购买的物品清单只有当项目实际上已经买了.但是,我目前的技术是在需要时产生无限循环的项目[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;
}
Run Code Online (Sandbox Code Playgroud)
(在此代码之前,数组被声明为:)
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];
Run Code Online (Sandbox Code Playgroud)
你的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(" ");
}
}
Run Code Online (Sandbox Code Playgroud)
至 :
for (int i = 0; i < need.length; i++) {
if (bought[i]){
System.out.print(need[i] + " ");
}
}
System.out.println(" ");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
424 次 |
| 最近记录: |