for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
is really (the (-h) is simply -1*h)
for (int i = 0; i < (BRICKS_IN_BASE - h); i++)
due to operator precedence
Question
Hi I'm learning Java and found a solution that is pretty neat, but I'm interested in a particular line of code in the 2nd for loop. I wouldn't know who to ask because I'm not in school for Java yet so I'm asking here, but anyway:
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
Does this mean that 'repeat i
for this number of times' is added' to 'h
minus 1'? More specifically what is (-h)
? Is it a pre-increment? And why is it in parenthesis?
It's again used in declaring the variable x
.
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class Pyramid extends GraphicsProgram {
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Width of each brick in pixels */
private static final int BRICK_HEIGHT = 12;
/** Number of bricks in the base of the pyramid */
private static final int BRICKS_IN_BASE = 15;
public void run() {
for (int h = 0; h < BRICKS_IN_BASE; h++)
{
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
{
int k = i * BRICK_WIDTH;
int m = h * BRICK_HEIGHT;
int x = ((getWidth() - ((BRICKS_IN_BASE + (-h)) * BRICK_WIDTH)) / 2) + k;
int y = getHeight() - ((BRICK_HEIGHT + 1) + m);
GRect brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT);
add(brick);
}
}
}
}
Solution
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
is really (the (-h) is simply -1*h)
for (int i = 0; i < (BRICKS_IN_BASE - h); i++)
due to operator precedence