【发布时间】:2021-10-07 22:50:37
【问题描述】:
我一直在研究“Head First Java”,并在看似相当简单的问题上花费了大量时间。然而,我一生都无法弄清楚为什么 maybeNew 方法看似随机递增。我花了很多时间假设它是死代码。
在这种情况下,return 1 是否也可以用作索引增加器?
代码输出为 14 1。
书中的问题是计算给定以下代码会输出哪些不同的流控制示例:例如例如,x
count = count + m4a[x].maybeNew(x);
感谢您的耐心等待。
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; // 1;, 2;
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index) { // index = 0;
if (index < 5) {
Mix4 m4 = new Mix4(); // m4 0 - 4; rn = 1;
m4.counter = m4.counter + 1; // 1.
// System.out.println(index);
return 1;
}
return 0;
}
}
【问题讨论】:
-
当您说“方法递增”时,我不明白您的意思。你的意思是一些变量的值递增,当方法运行时?如果是这样,哪个,以及你为什么不期待这个? “代码输出为 14 1。”请准确解释您认为答案应该是什么,并逐步解释您的逻辑。您的代码 cmet 不足以让我理解您的想法。
-
是的,也不确定你所说的“方法增量”是什么意思,
maybeNew总是return1 或 0。 -
count = count + 1; count = count + m4a[x].maybeNew(x);这两行将始终将count增加1 或2,具体取决于maybeNew是返回1 还是0。这是您有疑问的地方吗? -
你特意调出了
count = count + m4a[x].maybeNew(x);这行代码。你的意思是你对这条线上发生的事情感到困惑吗?根据您调试代码的尝试,您认为这一行似乎发生了什么?你认为应该怎么做? -
如果 Java 是您尝试学习的第一个编程语言,那么 Head First Java 不是您应该使用的书。它在介绍部分明确告诉您。
标签: java methods return increment return-type