我的代码假设采用一个数组,如果数字的值与数组中的零相邻,则将其值减半。我正在尝试修复代码中的错误,如果该错误与数字零相邻且零在数组的第一个或最后一个位置,则无法正确减少数组中的数字。我希望我的代码输出以下内容:
Day 0: {0,6,7,9,3,5,6,1}
Day 1: {0,3,7,9,3,5,6,1}
Day 2: {0,1,7,9,3,5,6,1}
Day 3: {0,0,7,9,3,5,6,1}
Day 4: {0,0,3,9,3,5,6,1}
Day 5: {0,0,1,9,3,5,6,1}
Day 6: {0,0,0,4,3,5,6,1}
Day 7: {0,0,0,2,3,5,6,1}
Day 8: {0,0,0,1,3,5,6,1}
Day 8: {0,0,0,0,1,5,6,1}
Day 9: {0,0,0,0,0,5,6,1}
Day 10: {0,0,0,0,0,2,6,1}
Day 11: {0,0,0,0,0,1,6,1}
Day 12: {0,0,0,0,0,0,6,1}
Day 13: {0,0,0,0,0,0,3,1}
Day 14: {0,0,0,0,0,0,1,1}
Day 15: {0,0,0,0,0,0,0,1}
Day 16: {0,0,0,0,0,0,0,1}
Day 17: {0,0,0,0,0,0,0,0}
---extinct---
但是它改为输出:
Day 295279: 0, 0, 7, 9, 3, 5, 6, 1.
Day 295280: 0, 0, 7, 9, 3, 5, 6, 1.
Day 295281: 0, 0, 7, 9, 3, 5, 6, 1.
Day 295282: 0, 0, 7, 9, 3, 5, 6, 1.
Day 295283: 0, 0, 7, 9, 3, 5, 6, 1.
Day 295284: 0, 0, 7, 9, 3, 5, 6, 1.
Day 295285: 0, 0, 7, 9, 3, 5, 6, 1.
它不断重复到无穷大,我不确定为什么会这样。这是我的代码:
public class Final {
public static void main(String[] args) {
int[] settlement = {0,6,7,9,3,5,6,1};
int daycont=0;
System.out.println("Day 0: "+settlement[0]+", "+settlement[1]+", "+settlement[2]+", "+settlement[3]+", "+settlement[4]+", "+settlement[5]+", "+settlement[6]+", "+settlement[7]+".");
while(settlement[0]!=0 || settlement[1]!=0 ||settlement[2]!=0 || settlement[3]!=0 || settlement[4]!=0 || settlement[5]!=0 || settlement[6]!=0 || settlement[7]!=0) {
daycont++;
for (int i=0; i<7; i++) {
if (settlement[i]==0) {
if(i!=7){
i++;
settlement[i]= settlement[i]/2;}
if(i!=1 && i!=0)
i=i-2;
settlement[i]= settlement[i]/2;
i++;
}
}
System.out.println("Day "+daycont+": "+settlement[0]+", "+settlement[1]+", "+settlement[2]+", "+settlement[3]+", "+settlement[4]+", "+settlement[5]+", "+settlement[6]+", "+settlement[7]+".");
}
for (int extcounter=0; extcounter<8; extcounter++) {
if (settlement[extcounter]==0) {
extcounter++;
if (extcounter==8)
System.out.println("----EXTINCT----");
}
}}
}
有人可以解释为什么它无法正常工作吗?我很困惑,我尝试使用Google搜索和浏览堆栈溢出问题,但是找不到任何东西。 (请注意,我使用的是一维数组,并且我最近才刚开始使用Java,所以我有一个非常基本的了解,而我在Stack Overflow上看到的一些代码我却不太了解)。谢谢。 :D
答案 0 :(得分:0)
我认为这应该可以完成任务。
for(i=0;i<7;i++)
{
if(i<6&& settlement[i]==0 && settlement[i+1]>0)
{
settlement[i+1]=settlement[i+1]/2;
}
}
答案 1 :(得分:0)
尝试一下:
for (int i = 0; i < settlement.length; i++) {
if (settlement[i] == 0) {
if (i != settlement.length - 1) {
settlement[i + 1] = settlement[i + 1] / 2;
}
if (i != 0) {
settlement[i - 1] = settlement[i - 1] / 2;
}
}
}