我是Java中的新手,我試圖編寫一個彈跳球程序。它應該在屏幕上的預先確定的位置創建一個球,並且球應該反彈離開屏幕。當我把所有的方法放在一個類中時,它完美地工作。但是,當我嘗試使用兩個類來完成任務時,我失敗了。Java:調用錯誤類的方法
這裏是球類基本上只是創建新球:
import acm.graphics.*;
import acm.program.GraphicsProgram;
import java.awt.Color;
import java.util.Random;
public class Ball extends GraphicsProgram{
private GOval ball;
private int diam;
public Ball(int width, int height){
Random rand = new Random();
diam = rand.nextInt(15) + rand.nextInt(15);
ball = new GOval(width, height, diam, diam);
Color c = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
ball.setFillColor(c);
ball.setFilled(true);
add(ball);
}
public Ball(){
Random rand = new Random();
diam = rand.nextInt(15) + rand.nextInt(15);
ball = new GOval(50, 100, diam, diam);
Color c = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
ball.setFillColor(c);
ball.setFilled(true);
add(ball);
}
public int getDiam(){
return(diam);
}
}
,這裏是應該延長球類的類:
//import acm.graphics.*;
//import acm.program.GraphicsProgram;
import java.awt.Color;
import java.util.Random;
public class BouncingBall extends Ball{
private final static int START_X = 50;
private final static int START_Y = 100;
private final static int GRAVITY = 3;
private final static double BOUNCE_REDUCE = 0.90;
private final static int DELAY = 50;
private final static double X_VEL = 5;
private double xVel = X_VEL;
private double yVel = 0.0;
private Ball ball;
private int diam;
public static void main(String[] arg){
new BouncingBall().run();
}
public void run(){
setup();
while(ball.getX() < getWidth()){
moveBall();
checkForCollision();
pause(DELAY);
}
remove(ball);
}
private void setup(){
ball = new Ball(START_X, START_Y);
}
private void moveBall(){
yVel += GRAVITY;
ball.move(xVel, yVel);
}
private void checkForCollision(){
diam = ball.getDiam();
if (ball.getY() > getHeight() - diam){
yVel = -yVel * BOUNCE_REDUCE;
double diff = ball.getY() - (getHeight() - diam);
ball.move(0, -2 * diff);
Random rand = new Random();
Color c = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
ball.setFillColor(c);
c = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
setBackground(c);
}
}
}
讓我困擾的是下面的。我得到的BouncingBall類錯誤,在該行
ball.move(xVel, yVel);
,線
ball.move(0, -2 * diff);
和線
ball.setFillColor(c);
,我得到的錯誤是「類java.awt中的方法舉措。組件不能應用於給定的類型;「前兩次出現,後一次出現「找不到符號」。這兩者都是因爲移動和setFillColor被錯誤的類而不是GObject類查找,就我所知它應該提供它的方法繼承到Ball然後 - 到BouncingBall。
我似乎無法找到一個解釋,爲什麼不是被稱爲繼承的方法 - 我會很感激,如果有人能幫我。
謝謝!
在您共享有沒有叫 – Marcus
球級「動」這將有助於如果我們能看到類GraphicsProgram,因爲我們不知道'move'方法是如何實現的根本方法的代碼。 –
'BouncingBall'是'Ball'的一個子類。你爲什麼要創建一個私人的'Ball'變量? – unholysampler