我有這個練習完美的工作:的mouseMoved給空例外指針 - 徹底難倒了(更斯坦福CS106疼痛)
import acm.program.*;
import acm.graphics.*;
import java.awt.event.*;
public class ProgramHierarchy extends GraphicsProgram {
public void run() {
Paddle = new GRect(0,getHeight() - 30,100,20);
add(Paddle);
addMouseListeners();
}
public void mouseMoved(MouseEvent e) {
if(e.getX() - Paddle.getWidth()>0) {
Paddle.move(e.getX()-Paddle.getX()-Paddle.getWidth(), 0);
}
}
private GRect Paddle;
}
但是,當我在一個較大的項目中使用完全相同的代碼,我的日食投空指針異常,甚至徹底崩潰的日食,我打我的桌子,說壞事,我不希望我的家人聽到。我的eclipse副本是否損壞?可能會發生什麼?
這是我較大的硬碰撞項目。
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Breakout extends GraphicsProgram {
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
private static final int PADDLE_Y_OFFSET = 30;
private static final int NBRICKS_PER_ROW = 10;
private static final int NBRICK_ROWS = 10;
private static final int BRICK_SEP = 3;
private static final int BRICK_WIDTH =
(WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP)/NBRICKS_PER_ROW;
private static final int BRICK_HEIGHT = 8;
private static final int BALL_RADIUS = 10;
private static final int BRICK_Y_OFFSET = 70;
private static final int NTURNS = 3;
private static final int DELAY = 30;
public void run() {
setup();
GRect Paddle = new GRect(0,HEIGHT - PADDLE_HEIGHT - PADDLE_Y_OFFSET,PADDLE_WIDTH,PADDLE_HEIGHT);
add(Paddle);
addMouseListeners();
}
private void setup() {
int xStart = (WIDTH - ((NBRICKS_PER_ROW * BRICK_WIDTH) + ((NBRICKS_PER_ROW -1) * BRICK_SEP)))/2;
int y = BRICK_Y_OFFSET;
for (int i = 0; i< NBRICK_ROWS; i++) {
int x = xStart;
for (int j = 0; j < NBRICKS_PER_ROW; j++) {
GRect block = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
if (i<2) {
block.setColor(Color.RED);
block.setFilled(true);
block.setFillColor(Color.red);
}
if (i==2||i==3) {
block.setColor(Color.orange);
block.setFilled(true);
block.setFillColor(Color.orange);
}
if (i==4||i==5) {
block.setColor(Color.yellow);
block.setFilled(true);
block.setFillColor(Color.yellow);
}
if (i==6||i==7) {
block.setColor(Color.green);
block.setFilled(true);
block.setFillColor(Color.green);
}
if (i==8||i==9) {
block.setColor(Color.cyan);
block.setFilled(true);
block.setFillColor(Color.cyan);
}
add (block);
x=x+BRICK_WIDTH + BRICK_SEP;
}
y=y+BRICK_HEIGHT+BRICK_SEP;
}
}
public void mouseMoved(MouseEvent PadX) {
if(PadX.getX() - Paddle.getWidth()>0) {
Paddle.move(PadX.getX()-Paddle.getX()-Paddle.getWidth(), 0);
}
}
private GRect Paddle;
}
這是[標籤:功課]如果是這樣,那麼標記它是有利的。 – 2012-07-22 22:48:32
沒有堆棧跟蹤,這是浪費時間,它會很快關閉 – 2012-07-22 22:49:12
另外,無論何時你看到一個NullPointerException(NPE),你應該仔細檢查導致異常被拋出的那一行,因爲在那一行是一個空的變量並且你正在嘗試使用。什麼原因導致你現在的NPE被拋出?我也同意你應該發佈整個堆棧跟蹤(整個錯誤信息)。 – 2012-07-22 22:49:45