我问这个是因为我想知道它为什么 - 而不是我应该做些什么来规避这个问题。我真的只想要一个技术解释为什么数学运算中的getWidth()(分配给currentXMargin)没有返回值。我GLabel的testValue1和testValue2; testValue1显然返回正确的像素数量,而testValue2返回-210(当然是金字塔的一半);它需要说167(就像testValue1那样我在其中硬编码公式)。更重要的是,当我尝试在GRect构造函数中使用currentXMargin时,它也无法在那里工作,返回相同的resuts(如果我使用变量则为-210,如果我只是对公式进行硬编码,则为正确的量),以及金字塔底座位于屏幕左侧的中间位置。
那么为什么getWidth没有为currentXMargin赋值中的操作返回一个值(在run方法下面)?
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;
/** Height 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;
public void run() {
double testValue1 = (getWidth() - (BRICKS_IN_BASE * BRICK_WIDTH))/2;;
GLabel test = new GLabel("width: "+testValue1,0,10);
add(test);
double testValue2 = currentXMargin;
GLabel test2 = new GLabel("width: "+testValue2,0,20);
add(test2);
//doRow();
}//run
private int brickCount = BRICKS_IN_BASE;
private double currentXMargin = (getWidth() - (BRICKS_IN_BASE * BRICK_WIDTH))/2;
private double currentYMargin;
GRect brick[] = new GRect[14];
private void doRow(){
for(int i=0;i<brickCount;i++){
brick[i] = new GRect(currentXMargin,10,BRICK_WIDTH,BRICK_HEIGHT);
add(brick[i]);
currentXMargin += BRICK_WIDTH;
}
currentYMargin -= BRICK_HEIGHT;
brickCount -= 1;
}//doRow
}//class
答案 0 :(得分:0)
0
是数字类型的默认值,直到它们被初始化。您在实例字段初始化期间调用getWidth()
,即在宽度尚未初始化的时候。