user1156596
user1156596

Reputation: 601

Head First Java 2nd Edition - Page 118, chapter 5

i'm going through an exercise called be the jvm.

However, the output that I am supposed to get is completely different to the way i have worked it out.

I reach y being 15, and my x is 7.

But the output should show 13 15 x = 6;

Here is the code:

 class Output {  

    public static void main (String [] args ) {  
        Output o = new Output();  
        o.go();  
    }  

    void go() {  
        int y = 7;  
        for (int x = 1; x < 8; x++) {  
            y++;  

            if ( x > 4 ) {  
            System.out.print(++y + " " );  
            }  

            if ( y > 14) {  
                System.out.println("x = " + x );  
                break;  
            } // close if   
        }  // close for  
    }  // close go  
} // close class  

could someone walk through the code with me, and show me where I am exactly going wrong?

Thank you for your help!

Upvotes: 0

Views: 1341

Answers (2)

Ben Maxfield
Ben Maxfield

Reputation: 655

Okay,

You start with a new output to call the method go().

When this method runs you have two variable, y=7 and x=1 (x defined within the for loop).

Pay attention to the format of the for loop, it states x is initialised at 1 and only continues until x < 8 which means when x==7, STOP. Don't process anything in the loop if x is EQUAL to 8.

Each loop increments x by one as defined by x++

So, stepping through the loop from the start, where x== 1 and y==7 increment y by one (y++).

now we have x==1 and y==8

we can ignore the next two if statements as x is less than 4 and y less than 14, so back to the start of the for loop, don't forget to increment x by one.

So for the second loop we have: x==2 y==9.

Third loop: x==3 y==10

Fourth loop: x==4 y==11 <- x is now 4, but not GREATER than 4. So on the next loop we need to enter the if(x>4) loop.

Fifth loop: x==5 y==12 (as y++ immediately) but then we enter the loop for when x>4 now, therefore we ++y. This is probably where you made a mistake

++y is similar to y++ but increments the value, then evaluates and stores it instead of evaluating the value, then incrementing and storing it.

This outputs 13 and now y==13.

Sixth loop: Same as the fifth loop (logically, enter the first if statement!) x==6 y==13

output 15 and now y==15, so we can enter the final loop, so we output the value of x for this loop,

which is 6.

We then break out and that's the end.

So the output, should be 13 15 x=6. I hope this helps, just be aware of the difference between ++y and y++.

Upvotes: 2

SpongeBobFan
SpongeBobFan

Reputation: 964

I've got this:

x | y      | output
1 | 8      |
2 | 9      |
3 | 10     |
4 | 11     |
5 | 12, 13 | 13
6 | 14, 15 | 15 x = 6

Hope it will help you to find your mistake

Upvotes: 0

Related Questions