簡體   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