I did not understand the operation of the code below, maybe later in the book have better explanations or let something even pass in the review.
I will detail the points in the code that I have doubts about.
package qb5;
public class Qb5 {
static class Mix4{
int counter = 0;
public int maybeNew(int index){
if (index < 7 ){
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1; //Sempre retornará 1, aqui entendi
}
return 0; //Não achei o porque do return 0 neste ponto
}
}
public static void main(String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x < 7 ){
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count += 1;
count = count + m4a[x].maybeNew(x);
x +=1;
}
System.out.println(count + " " + m4a[1].counter); //Porque m4a[1]?
}
}
Here I have the biggest doubt:
I understand that maybeNew(x)
, sends the value for the index variable in the maybeNew
method to make the comparison, but that same maybeNew(x)
somehow affects the assignment of the count
variable itself % of the beginning of the line?
The output of this exercise would be 14 1, but I got lost and I can not see how it got to 14, the 1 itself return
indicates the value.
EDIT:
This code is really tricky, just like another one, but the book itself says there are things that will be clarified ahead, suggesting that you pass on if you do not understand, but I preferred to hit the head.
From what I understand, the variable counter
only goes to confuse it, it will always be 1.
As long as m4a[1].counter
that index 1 is embellishment, because I put 2 and also returned result 1 of the counter.
@Edjane cleared the mind by explaining the instance to zero the variable.
I made a manual debug by adding a few more prints in the code and seeing the output, and next to the table test by @Maniero I saw that they did not beat the results, so I managed to understand.
I made a loop of 3 just to not get large the image, because in the output of m4
printed 2 times, I did not find the cause of it, it is banal thing but to finish,