Understanding exercise of the book Use the Java Head

0

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,

    
asked by anonymous 04.09.2018 / 02:54

3 answers

2

I studied many exercises of this type to take OCJP certification, it covers class instantiation and passing values, for example, because this line,

m4.counter = m4.counter + 1;

contained in method public int maybeNew (int index) always returns 1? Simply by the fact that whenever the method is invoked in main this value is restarted when you instantiate the class.

 Mix4 m4 = new Mix4();
  

This is to test you and try to mislead you if you do not   dominate this, you can deduce that m4.counter = m4.counter + 1; is always   increasing 1 to the previous value, which would give a different answer.

In this case you can even put the if return as m4.counter that will always return 1.

Another important point, see the comments in the code

    while (x < 7 ){
            m4a[x] = new Mix4(); //aqui nova instancia, ou seja, sempre é inicializado
            m4a[x].counter = m4a[x].counter + 1; //por ser inicializado sempre soma 0+1, ou seja aqui sempre vai ser 1
            count += 1; //aqui ele pega o valor anterior do count que não é inicializado e acrescenta 1
            //nesse ponto você percebe que a variável não instanciada continua com o seu valor anterior
            count = count + m4a[x].maybeNew(x); //soma o valor anterior com o valor passado pelo método, como você esta indo ate 7 ele passa 1, caso você faça um while maior que 7 ele passa 0

       x +=1;
    }
  

The output of this exercise would be 14 1, but I got lost and I can not   fill in how it came to 14

Because the result is 14 1 let's put in the cycle ok?

1° ciclo:
m4a[x].counter = 1;
count += 1;
count = 1;
count = 1 + 1; // count = 2

2° ciclo:
m4a[x].counter = 1;
count += 1; //valor anterior = 2 + 1 = 3
count = 3;
count = 3 + 1; // count = 4

...
7° ciclo:
m4a[x].counter = 1;
count += 1;
count = 13;
count = 13 + 1; // count = 14
     

Result 14 1

What if you overtake 7 in the while causing the if to return 0? Example:

while (x < 8 )
8° ciclo:
m4a[x].counter = 1;
count += 1;
count = 15;
count = 15 + 0; // count = 15
     
    

Your final result would be 15 0

  

Continuing ...

  

Already in the m4a [1] .counter window that index 1 is garnish, because   I put 2 and also returned result 1 of the counter

This value is not really embellished, it always gives the same value because it is always created a new instance, this is more an intention of you to be induced that this value has increased, which does not happen, for you to understand better, let's get this snippet of your code:

static class Mix4{
  int counter = 0;
  ...

Now, we have this section:

if (index < 7 ){
    Mix4 m4 = new Mix4(); //nova instância de Mix4
    m4.counter = m4.counter + 1; // isso é a mesma coisa que ***m4.counter = 0+1***

In this case the value received for m4.counter sum is 0 because it took the counter value set in the Mix4 class. As long as you do not instantiate this class again this value within that if will be 1 (m4.counter = 0 + 1 = > 1)

Example:

if (index < 7 ){
    Mix4 m4 = new Mix4();
    m4.counter = m4.counter + 1; //m4.counter = 0 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 1
    m4.counter = m4.counter + 1; //m4.counter = 1 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 2

Another test to be clearer, and if the counter value was 4

static class Mix4{
      int counter = 4;
      ...

Result:

if (index < 7 ){
    Mix4 m4 = new Mix4();
    m4.counter = m4.counter + 1;  //m4.counter = 4 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 5
    m4.counter = m4.counter + 1; //m4.counter = 5 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 6

Working with Java, you will never write or see such a code, unless you are a teacher. But these teachings are key to a good dsenvolvedor.

  

... because in m4 output you printed 2 times

I did not see why it was being printed twice

    
04.09.2018 / 17:54
5
return 1; //Sempre retornará 1, aqui entendi

Not always, it will only return if index is less than 7.

return 0; //Não achei o porque do return 0 neste ponto

It will execute whenever index is not less than 7. The function must have a return in any circumstance, it can not return something only in some cases and in another case not.

  

this same maybeNew (x) somehow affects the assignment of the count variable itself at the beginning of the line?

It itself does not, but the whole line is affecting count , after all this line is saying to save in count , and this in itself already affects something, a value that in this case is count added of an expression

System.out.println(count + " " + m4a[1].counter); //Porque m4a[1]?

We can not know what's in the question, but for some reason it needs to get the second element of this array .

  

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.

He followed the algorithm. I could explain it line by line, but you'd better do the table test and identify. But in confusing code so the best is neither to try . Learn from something more meaningful. Understanding this will be detrimental to your learning.

Rarely main() must be next to a class that needs to be instantiated. This confuses everything. There is no reason for every part of this class to exist and if you start working with nonsense things you will get used to it. Note that in each step there is the accumulation of 2. The first accumulation is quite explicit and then the other happens because maybeNew() always returns 1, this could have been written in a row.

It's not your fault to have difficulty understanding, it's the code's fault.

The code is poorly written and not very educational. It teaches to do strange, confusing and probably wrong things, so I would question the book. This series of books was well-regarded, so I do not know if it got worse over time or it was specifically misspelled.

    
04.09.2018 / 03:04
2

This is a very confusing code and like @Many said it is questionable as a code to be in a book, but I will try to explain what is happening on the basis that this is the only project code.

Everything starts in its main , where the class attributes are nominated and instantiated:

int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;

Then it does a loop that will iterate 7 times by increasing the x value at each iteration

while (x < 7 ) // itera 7 vezes de x=0 até x=6

x +=1; //aumenta o valor de x a cada iteração

Well let's look at the four lines of code inside the loop (analyze what the code is doing =))

    m4a[x] = new Mix4();                   //linha 1
    m4a[x].counter = m4a[x].counter + 1;   //linha 2
    count += 1;                            //linha 3
    count = count + m4a[x].maybeNew(x);    //linha 4

In line 1 main creates an instance of Mix4 and places it in the m4a

In line 2 the code is taking that instance that is now in the list and adding the value 1 to the attribute of that object, in this case the counter , which was 0 and is now 1 < p>

In line 3 the code adds the value 1 to the variable count , since this code is executed 7 times we can say that this line is responsible for adding the value 7 to the variable co_de %

In line 4 the code is taking the value of count adding a value to it * and saving that sum to itself count variable, we can say that is adding a value to the value it already had before.

Let's look at this added value:

The code is calling the count method of the object that was just saved in the list, what do we know about it?

- > We know that the value of its maybeNew attribute is equal to 1, and that the passed parameter (x) is always less than 7

Analyzing the counter method:

The method has as a first line a maybeNew that checks if the passed parameter is less than 7 (which we know it always is) and does a series of thing if this condition is true.

 Mix4 m4 = new Mix4();
 m4.counter = m4.counter + 1;
 return 1;

First creates a new instance and assigns it to an object called if , then modifies the attribute value of the object m4 and finally returns the value 1

Then we know that it will always return 1 and we now know how much is added to m4 in line 4

Knowing that in the line 4 is always added 1 we have that at the end of the 7 iteration will be added the value 7.

System.out.println(count + " " + m4a[1].counter); 

We have reached the result of 14

The value of count is one that the code had added to line 2

I hope to have helped, any questions leave a comment

    
04.09.2018 / 13:47