Hi,

I am doing an exercise of Head First Java Pool puzzle. I tried many times and finally got the output required but I am still not fully understand that how program produced that output.
The code for Pool Puzzle is as under:

class Echo {
   
   int count = 0;
   void hello() {
      System.out.println("helloooo...");
   }
}
public class EchoTestDrive {
   
   public static void main (String []args) {
      
      Echo e1 = new Echo();
      Echo e2 = new Echo();
      
      int x = 0;
      
      while ( x < 4 ){
         
         e1.hello();
         e1.count = e1.count + 1;
         
         if ( x > 0){
            
            e2.count = e2.count + 1;
         }
         
         if ( x > 1) {
            
            e2.count = e2.count + e1.count;
         }
         
         x = x + 1;
         
      }
         System.out.println(e2.count);
   }

}

The program prints to the output is ;

helloooo...
helloooo...
helloooo...
helloooo...
10

=======================

Also if someone could tell me that how we can get the same output but instead of 10 we need 24.

I hope my question will be answered quickly.

Thank you.

Have you tried adding printlns to the code to see what controls how many times it prints?
Print out the values of the variables that are used to see how they change and how they relate to the output.

No,

I didn't do anything like that and you are the one who told me that about Java. As I am new to java so don't know much about it and I haven't got any previous programming experience. Would you mind to tell me how I can do that, please.

I appreciated that you replied to my post.

Thank you.

System.out.println(e2.count);

this line is a print, it prints the value of the count variable of your instance of echo.
if you add a print statement in your while loop, you will see how many times it runs.
if you copy the above print within the while loop, you can see for each iteration what the value is.

Add an Id String to what is printed out. You should add several of these printlns to the code to see how the value changes at many places. In stead of just printing the number, include a unique identifying String on each println:

System.out.println("1 e2.cnt=" + e2.count);

Thank you very much all of you helped me out with this puzzle. I hope all of you will be helping me with my on ward queries. Thank you so much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.