Head First Java 2nd Ed- Page 44,Chaper 2

时间:2017-01-02 06:54:47

标签: java

所以我对第一个java中的游戏拼图有点困惑。我还无法完全理解逻辑如何在这段代码上工作。我想知道为什么这段代码的输出是10。

以下是代码:

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 += 1;

            if(x==3){
               e2.count +=1;
            }

            if(x>0){
               e2.count =e2.count + e1.count;
            }
            x += 1;
         }

         System.out.println(e2.count);
   }
}

有人可以指导我吗? (Noob在这里)。

3 个答案:

答案 0 :(得分:1)

以下列表显示每个循环后变量的状态:

循环1:

  • x = 0
  • e1.count = 1(第9行)
  • e2.count = 0

循环2:

  • x = 1
  • e1.count = 2(第9行)
  • E2。 count = 2(第16行=&gt; x > 0

循环3:

  • x = 2
  • e1.count = 3(第9行)
  • e2.count = 2 + 3 = 5(第16行)

循环4(最后):

  • x = 3
  • e1.count = 4(第9行)
  • e2.count = 6(第12行)
  • e2.count = 6 + 4 = 10(第16行)

答案 1 :(得分:0)

我已完成那一章。所以我知道 Echo 类中的内容是什么,这个问题是什么。 :)试试这段代码。

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=e1.count+1;
            if(x==3)
                e2.count=e2.count+1;

            if(x>0)
                e2.count=e2.count+e1.count;
            x++;
        }
        System.out.println(e2.count);
    }
}

答案 2 :(得分:0)

  

我想知道为什么这段代码的输出是10。

所以这条线让我对它进行逆向工程。和班级Echo应类似于以下内容:

class Echo
{
     public int count; 
     void hello() { // ... }    
}

在main方法中添加一些print语句以查看流程:

public static void main(String [] args){
        Echo e1 = new Echo();
        Echo e2 = new Echo();

        int x =0;
        while(x<4){
            //e1.hello();
            e1.count += 1;
            System.out.println("e1.count = " + e1.count);

        if(x==3){
            e2.count +=1;
            System.out.println("e2.count = " + e2.count);
        }

        if(x>0){
            System.out.println("e2.count = " + e2.count +"+"+ e1.count);
            e2.count =e2.count + e1.count;
            System.out.println("e2.count = "+ e2.count);
        }
        x += 1;
      }
        System.out.println(e2.count);
    }