繁体   English   中英

我不明白这段代码背后的逻辑。 有人可以向我解释它的真正作用和方式吗?

[英]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);
  
   
  }
}

我已经重新格式化了代码:

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);
    }
}

如果我们看一下 while 循环:

1)在第一个循环之后(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(如 x=3)

e2.count = 6 + 4 = 10

因此,您的 output 是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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