Reputation: 47
This question is not a problem that needs to be solved, rather an aspect of my code that I'd like some help with understanding.
I first draw a line in the middle of the screen to make it easier to explain what I don't understand.
The user can enter how many pixels are between each line.
Explanation of the loop: it draws a line from the middle of the left side Y-axis to the bottom right hand corner and then repeats that action increasing the startY integer by userInput and decreasing the endY integer by the same amount until the bottom of the frame has been reached.
g.setColor(Color.RED);
g.drawLine(startX, getHeight() / 2, endX, getHeight() / 2);
g.setColor(Color.BLACK);
for (int startY = getHeight() / 2; startY <= bottom; startY += userInput) {
g.drawLine(startX, startY, endX, endY);
endY -= userInput;
}
}
This is the effect: https://i.sstatic.net/jYdwr.png
Now when I switch these lines of code:
g.drawLine(startX, startY, endX, endY);
endY -= userInput;
to
endY -= userInput;
g.drawLine(startX, startY, endX, endY);
This is the effect: https://i.sstatic.net/T9IEd.png
As you can see it draws an extra line on the right side so that means the loop is executed an extra time right? I don't understand why. Shouldn't both versions of the loop stop at the same time (when the bottom of the frame is reached)?
So why does the loop execute an extra time when I switch up these statements?
I'm quite confused and I'm having trouble wrapping my head around this logic.
Upvotes: 2
Views: 86
Reputation: 318
In both cases, when the bottom of the frame is reached it draws the line for the last time.
In the first case, it draws the line from the bottom to the top and then decrements the endY variable (which in this case isn't relevant anymore). In the second case, it decrements first, which is why the line goes above your red line.
If you can't get your head around this, try to set the pixels between each line to a bigger number and then try to traverse the for loop in your head. Take a paper and write down all the variables and what number they have stored at the moment. Probably also draw the lines yourself on the paper ;)
Upvotes: 3
Reputation: 665
Actually, the loop is not executed once more, but your output is offset by userInput
pixels, as one may expect since you decrement endY before drawing
Upvotes: 2