我是java的初学者。我正在练习第90页第4章,来自书籍java headfirst。我对输出感到困惑。为什么在本书中,在本练习的解决方案部分右输出为(x <9)和(索引<5)= 14 1.为什么我输出81?
请告知我的错误或解释错误。
public class Mix4 {
int counter = 0;
public static void main(String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x < 9){
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count = m4a[x].maybeNew(x);
x = x + 1;
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index){
if (index < 5){
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return counter;
}
return index;
}
}
答案 0 :(得分:2)
错误在第15行和第27行:
该行:
count = count = m4a[x].maybeNew(x);
应替换为
count = count + m4a[x].maybeNew(x);
该行:
return index;
应替换为:
return 0;
这将输出为14 1
这是根据您提到的书籍示例(Java Head First,第90页)