简体   繁体   中英

Can someone please explain to me what the java code here is doing?

I am learning java using the headfirst Java book. I have a problem understanding what some Java do and how an output came to be. For example:

class MultiFor {

 public static void main(String[] args) {
    // write your code here
        int x = 0;
        int y = 30;

        for (int outer = 0; outer < 3; outer++){
            for (int inner = 4; inner > 1; inner--){
                x = x + 3;
                y = y - 2;
                if (x == 6){
                    break;
                }
                x = x + 3;
            }
            y = y - 2;
        }
        System.out.println(x + " "  + y);
    }
}

my output is 54 6, but i don't know how it came to be. Can someone explain this?

The For-Loops works that way:

for(initialisation ; condition; steps){ do Stuff }

initialisation is the part where Variables are defined not necessary Variables for the condition but they are only reachable in the for-loop.

condition as long as the condition is true the will run again.

steps mostly an interation for the loops in this case its outer = outer +1 and inner = inner -1.

in this example the outer for-loop runs from outer=0 to outer=2 and the inner runs from inner = 4 to inner = 2. In the If-Condition is tested on x == 6 after reaching this true status it will stop the inner for-loop with a break;.

thats what it do how it reachs the expected values is just counting the loops and adding values.

Value of x and y are initialized 0 and 30 respectively. There are two loops, inner and outer. Outer loop would iterate three times and the inner loop would execute three times for every iteration of outer loop, but have a break condition when x would be 6. Following are the values of x and y after each iteration of the inner and the outer loop.

Iteration outer:0 Iteration inner :4 x =3 x =6 y =28 Iteration inner :3 x =9 x =12 y =26 Iteration inner :2 x =15 x =18 y =24

y =22

Iteration outer :1 Iteration inner :4 x =21 x =24 y =20 Iteration inner :3 x =27 x =30 y =18 Iteration inner :2 x =33 x =36 y =16

y =14

Iteration outer :2 Iteration inner :4 x =39 x =42 y =12 Iteration inner :3 x =45 x =48 y =10 Iteration inner :2 x =51 x =54 y =8

y =6

Hence the final value of x and y would be 54 and 6 respectively.

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