Understanding the exercise of the book Use the Java Head

Asked

Viewed 306 times

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.

Lógica java

  • 1

    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 "

  • I edited the answer to make it clearer. Good study!

3 answers

5

return 1; //Sempre retornará 1, aqui entendi

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

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

He will execute whenever index is not less than 7. The function needs to have a return in any circumstance, it cannot return something only in some cases and in other not.

that same maybeNew(x) affects somehow the assignment of the Count variable itself from the beginning of the line?

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

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

We have no way of knowing what’s in the question, but for some reason he needs to take the second element of this array.

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.

It was following the algorithm. I could explain line by line, but the best thing is to do it yourself table test and identify. However, in a confusing code so it’s best not to even try. Learn with something more meaningful. Understanding this will be detrimental to your learning.

Rarely the 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 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 you’re having trouble understanding, it’s the code’s fault.

The code is badly written and not very didactic. It teaches to do strange things, confused and probably wrong, so I would question the book. This series of books was highly regarded, so I don’t know if it got worse over time or this one specifically was badly written.

  • Thanks for the table test tip.

2

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

It all starts in your main, where the class attributes are named and instantiated:

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

Then make a loop that will iterate 7 times increasing the value of x 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 go 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 the line 1 the main creates an instance of Mix4 and put her on the list m4a

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

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

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

Let’s analyze this added value:

The code is calling the method maybeNew of the object that was only saved in the list, what we know of it?

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

Analyzing the method maybeNew:

the method has as its first line a if that checks if the parameter passed is less than 7 ( which we know it always is) and does a number of things 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 m4, then modifies the object attribute value m4 and finally returns the value 1

then we know that it will always return 1 and we now know how much has been added to the count in line 4

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

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

We come to the result of the 14

The value 1 of m4a[1].counter is the one the code had added to line 2

I hope I’ve helped, any doubt leave a comment

2


I studied a lot of exercises of this type to get OCJP certification, it covers instantiation of classes and passage of values, for example, because this line,

m4.counter = m4.counter + 1;

contained in the method public int maybeNew(int index) always returns 1? Simply because whenever the method is invoked in main this value is reset, when you instantiate the class.

 Mix4 m4 = new Mix4();

This is to test you and try to mislead you if you don’t master this, you can deduce that M4.counter = M4.counter + 1; always this incrementing 1 to the previous value, which would give a different answer.

In this case you can even put the return of the if 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 exit from this exercise would be 14 1, but I was lost and I can’t fill as it reached 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 exceed 7 no while causing 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 sáida m4a[1]. counter that index 1 is decorated, because put 2 and also returned 1 counter result

In fact this value is not of embellishment, 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 suffered an increment, what does not happen, for you to understand better, let’s take this excerpt of your code:

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

Now, we take this stretch:

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 defined in the Mix4 class. As long as you do not instantiate that class again that 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;
      ...

Upshot:

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 code, "unless you’re a teacher" but these teachings are fundamental to a good involve.

...because in M4 output printed 2 times

I didn’t see why I was printed twice

  • I did the test of adding 8, the final output is 15 1, because it is the counter, but in the debug print I did where I got this excerpt m4a[x].maybeNew(x) It really came out 0. I edited my topic with an image and a final question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.