I’m doing these free online Stanford classes and learning Java. I’m stuck on something and haven’t been able to figure it out. I think there must be something wrong with my logic. Please check out the code below. I commented it, so hopefully you can understand what I’m trying to do there.
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 = 14;
/** The Width of the Base in px */
double baseInPx = BRICKS_IN_BASE * BRICK_WIDTH;
/** Taking the width of the window minus the width of the base and dividing by two
* to find the x axis starting point)
*/
double firstBrick = (getWidth() - baseInPx) / 2;
/* giving the y axis a variable name */
double baseHeight = getHeight();
public void run() {
add(new GRect(firstBrick,baseHeight,BRICK_WIDTH, BRICK_HEIGHT));
}
}
I’m thinking I must be doing something wrong in my formatting in this line:
double firstBrick = (getWidth() - baseInPx) / 2;
The problem is that my variable in the x axis is not working. If I hard code a number there, the rect shows up, but not with firstBrick
Thanks for your help!
EDIT: Thank you all for your help! Pretty much every one of you were right. I just learned something!
Move both firstBrick and baseHeight into the run method and see if that works.
My guess is your getWidth() and getHeight() are instance methods, not static methods. So you can not call on them in your object initialization block (in your example code: the inits outside any methods) because the Pyramid object hasn’t been completely initialized.
You can also declare the variables where they are and initialize them in the Pyramid constructor, which is the preferred approach. That’s what constructors are for.