1
I did not understand the functioning of the code below, maybe later in the book have better explanations or missed something even in the review.
I will detail the points in the code itself in which I have doubts.
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 understood that maybeNew(x)
, sends the value to the variable index in the method maybeNew
to make the comparison, but that same maybeNew(x)
affects somehow the assignment of the variable itself count
from the beginning of the line?
The exit of this exercise would be 14 1, but I was lost and I can’t see how it reached 14, the 1 the own return
indicates the value.
EDIT:
This code is really tricky, just like the previous one, but the book itself says that there are things that will be clarified in front, soiling that pass forward if you do not understand, but I preferred to hit head.
From what I understand, the variable counter
only comes in to confuse even, she will always be 1.
Already on the Satyr m4a[1].counter
that index 1 is embellished, because I put 2 and also returned result 1 from the counter.
@Edjane cleared the mind by explaining from the instance zeroing the variable.
I debugged a manual by adding a few extra prints to the code and seeing the output, and next to the dirty table test by @Maniero I saw that the results did not match, so I was able to understand.
I made a loop of 3 just to not make the image great, because in the output of m4
printed twice, I did not find the cause of it, it is trivial thing but to finish, remained this doubt.
Please structure your doubt better, the code is mixed with doubt. Please put the doubt in a paragraph and right after the code, or vice versa for easy reading, and use two bars to signal comment in the code: " //COMMENT "
– Thiago Bomfim
I edited the answer to make it clearer. Good study!
– Edjane