Reputation: 31
I have been working through 'Head First Java', and spent an inordinate amount of time on what was seemingly a fairly simple question. And yet, could not for the life of me figure out why the method maybeNew seemingly randomly increments. I spent a good amount of time assuming it was dead code.
Does return 1 also operate as an index increaser in this case?
The code output is 14 1.
The question in the book was to work out what different flow control examples would output given the following code: e.g. having x < 19, and index < 1, for instance. Hence my confusion, given the code:
count = count + m4a[x].maybeNew(x);
Thank you for your patience.
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;
}
}
Upvotes: 0
Views: 62
Reputation: 11959
If that may help:
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;
}
The whole new Mix4()
is useless here: that's a dead variable because you don't really do anything with m4
.
So maybeNew
can be written as:
public int maybeNew(int index) { // index = 0;
if (index < 5) {
return 1;
}
return 0;
}
The whole maybeNew method could also be static
(independent of any instance of Mix4
):
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 + Mix4.maybeNew(x);
x = x + 1; // 1;, 2;
}
System.out.println(count + " " + m4a[1].counter);
Since the code only ever use m4a[1], the other index are not used; you can move the new Mix4
and further: simplify the loop:
int count = 0;
Mix4[] m4a = new Mix4[20];
m4a[1] = new Mix4();
m4a[1].counter = m4a[1].counter + 1;
int x = 0;
while (x < 9) {
count = count + 1 + Mix4.maybeNew(x);
x = x + 1; // 1;, 2;
}
System.out.println(count + " " + m4a[1].counter);
And finally, remove the array:
int count = 0;
Mix4 m4a = new Mix4();
m4a.counter = m4a.counter + 1;
int x = 0;
while (x < 9) {
count = count + 1 + Mix4.maybeNew(x);
x = x + 1; // 1;, 2;
}
System.out.println(count + " " + m4a.counter);
The loop can then be read:
count
9 timescount
= count = 14.
Upvotes: 1