我正在参加这些免费的斯坦福在线类(class)并学习 Java。我被某件事困住了,一直无法弄清楚。我想我的逻辑一定有问题。请查看下面的代码。我评论了它,所以希望你能理解我想做什么。
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));
}
}
我想我在这一行的格式中一定做错了什么:
double firstBrick = (getWidth() - baseInPx) / 2;
问题是我的 x 轴变量不起作用。如果我在那里硬编码一个数字,则会显示该矩形,但 firstBrick
感谢您的帮助!
编辑:谢谢大家的帮助!几乎你们每个人都是对的。我刚刚学到了一些东西!
最佳答案
将firstBrick和baseHeight都移到run方法中,看看是否有效。
public void run() {
double firstBrick = (getWidth() - baseInPx) / 2;
double baseHeight = getHeight();
add(new GRect(firstBrick,baseHeight,BRICK_WIDTH, BRICK_HEIGHT));
}
我的猜测是你的 getWidth() 和 getHeight() 是实例方法,而不是静态方法。因此,您不能在对象初始化 block 中调用它们(在示例代码中:任何方法外部的 inits ),因为 Pyramid 对象尚未完全初始化。
您还可以在 Pyramid 构造函数中声明变量并初始化它们,这是首选方法。这就是构造函数的用途。
关于java - 分配变量然后在参数中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2286350/