简体   繁体   中英

i do not get the logic behind this code. Can someone please explain to me what it really does and how?

class Echo{
  
  int count = 0;
  
  void hello(){
    
    System.out.println("hellooo...");
    
  }
  
}


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==3){
         
         e2.count = e2.count +1;
       }
       
       if (x>0){
         
         e2.count = e2.count + e1.count;
       }
       x=x+1;
     }
     System.out.println(e2.count);
  
   
  }
}

I have reformatted the code:

class Echo {
    int count = 0;
    void hello() {
        System.out.println("hellooo...");
    }
}

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

If we look at the while loop:

1) after first loop (x=0):

e1.count = 1

e2.count = 0

2) x=1

e1.count = 2

e2.count = 0 + 2 = 2

3) x=2

e1.count = 3

e2.count = 2 + 3 = 5

4) x=3

e1.count = 4

e2.count = 6 (as x=3)

e2.count = 6 + 4 = 10

Hence your output is:

hellooo...
hellooo...
hellooo...
hellooo...
10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM