在這個數組中,我試圖在每次循環后輸出每個元素的一半,直到數組的所有元素都變成零,如 [0,0,0,0,0,0,0,0]。假設我的數組是 [3, 6, 0, 4, 3, 2, 7, 1] 但我的程序在每個元素為零之后執行此操作,然后轉到下一個。第 1 天 [1, 6, 0, 4, 3, 2, 7, 1]第 2 天 [0, 6, 0, 4, 3, 2, 7, 1]第 3 天 [0, 3, 0, 4, 3] , 2, 7, 1]第 4 天 [0, 1, 0, 4, 3, 2, 7, 1]第 5 天 [0, 0, 0, 4, 3, 2, 7, 1]...怎么辦我像這樣在每次循環后將每個元素減半;第 0 天 [3, 6, 0, 4, 3, 2, 7, 0]第 1 天 [3, 3, 0, 2, 3, 2, 3, 0]第 2 天 [3, 1, 0, 1, 3] , 2, 1, 0]第 3 天 [3, 0, 0, 0, 3, 2, 0, 0]第 4 天 [1, 0, 0, 0, 1, 1, 0, 0]第 5 天 [0, 0, 0, 0, 0, 0, 0, 0]到目前為止,這是我的代碼:import java.util.Arrays;import java.util.Scanner;public class Zombi2 { public static void main(String[] args) { boolean cond = false; Scanner input = new Scanner(System.in); int[] inhabitants = new int[8]; for(int i=0; i<inhabitants.length; i++) { inhabitants[i] = input.nextInt(); } for(int x : inhabitants) { if(x != 0) cond = true; } int t = 1; while(cond) { cond = false; for(int x=0; x<inhabitants.length; x++) { while(inhabitants[x]>0) { inhabitants[x] = inhabitants[x]/2; if(inhabitants[x] != 0) cond = true; System.out.println("Day " + t + " " + Arrays.toString(inhabitants)); t++; } } } do { for(int x : inhabitants) { if(x != 0) cond = true; } }while(cond); System.out.println("---- EXTINCT ----"); }}
1 回答

catspeake
TA貢獻1111條經驗 獲得超0個贊
您必須交換循環。該while回路必須在外部和for環內:
我相信所有的整數都是正因此受到檢查,如果它們的總和為0,循環停止。
我認為這會奏效:
int sum = 1;
int day = 1;
while (sum > 0) {
sum = 0;
for (int x = 0; x < inhabitants.length; x++) {
if (inhabitants[x] > 0)
inhabitants[x] = inhabitants[x] / 2;
sum += inhabitants[x];
}
System.out.println("Day " + day + " " + Arrays.toString(inhabitants));
day++;
}
添加回答
舉報
0/150
提交
取消