New to Java, Line of code is stumping me
Hello all, thanks in advance for helping me out!
I'm reading Head First Java and an exercise is confusing me a little bit. The Original instructions of the exercise are irrelevant, however, the point is to be able to solve it with out just compiling the code and running it, which would just spit out the answer. I was unable to do this because a particular line in the code. Here is the original code, with one line added myself, which i've noted.
Code:
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; //This is the line confusing me
count = count + 1;
count = count + m4a[x].maybeNew(x);
System.out.println(count + " " + m4a[x].counter); //This is the line I added
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 1;
}
return 0;
}
}
The output is
2 1
4 1
6 1
8 1
10 1
11 1
12 1
13 1
14 1
14 1
The line I added was to see what the value of "m4a[x].counter" was at each position in the array, not just it's value at the 2nd position, as it is in the original code. What I'm confused about is why the the value of "m4a[x].counter" never changes, despite the the line "m4a[x].counter = m4a[x].counter + 1"
Again, thanks in advance for the help =)