我很好奇以下代码的输出为何为141。当我自己遍历该代码时,最终得到的是counter
等于2,count
等于4。我想确保只打印第二个索引,所以我们只循环两次,对吗?
package mix4;
公共类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 static int maybeNew(int index) {
if (index < 5) {
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}
您的if语句中的此代码不起作用
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
[m4
立即超出范围,不使用。