2016-12-04 73 views
-1

我有一個項目在我的(OOP)類中。這是任務:改變反彈方法,將球放置在屏幕上半部分的任意位置。編譯器錯誤不兼容類型:java.lang對象無法轉換

這是我應得的

import java.awt.Color; 
import java.util.ArrayList;     
import java.util.Random; 
/** 
* Class BallDemo - a short demonstration showing animation with the 
* Canvas class. 
* 
* @author Michael Kölling and David J. Barnes 
* @version 2016.02.29 
*/ 

public class BallDemo 
{ 
    private Canvas myCanvas; 
    private ArrayList ball; 
    private BouncingBall bounceBall; 
    private Random randomGenerator; 

    /** 
     * Create a BallDemo object. Creates a fresh canvas and makes it visible. 
     */ 
    public BallDemo() 
    { 
     myCanvas = new Canvas("Ball Demo", 600, 500); 
    } 

    /** 
     * Simulate two bouncing balls 
     */ 
    public void bounce() 
    { 
     int ground = 400; // position of the ground line 
     ball = new ArrayList(); 
     randomGenerator = new Random(); 

     myCanvas.setVisible(true); 
     myCanvas.erase(); 

     // draw the ground 
     myCanvas.drawLine(50, ground, 550, ground); 

     // create and show the balls 
     BouncingBall ball1 = new BouncingBall(position(),position(),16,Color.BLUE,ground,myCanvas); 
     ball1.draw(); 
     BouncingBall ball2 = new BouncingBall(position(),position(),20,Color.RED,ground,myCanvas); 
     ball2.draw(); 
     BouncingBall ball3 = new BouncingBall(position(),position(),20,Color.BLACK,ground,myCanvas); 
     ball3.draw(); 
     //Add balls to ArrayList 
     ball.add(ball1); 
     ball.add(ball2); 
     ball.add(ball3); 

     This is where I get the error: 

     // make them bounce 
     boolean finished = false; 
     while (!finished) { 
      myCanvas.wait(50);   // small delay 
      for(int i = 0; i < ball.size(); i++) { 
       **bounceBall = ball.get(i);**   
       bounceBall.move(); 

      // stop once ball has travelled a certain distance on x axis 
      if(bounceBall.getXPosition() >= 550) { 
       finished = true; 
      } 
     } 
    } 
} 

    /** 
    * Randomly generates the position 
    * Pick the number between 0 to 200 
    */ 

    public int position() { 
     return randomGenerator.nextInt(200); 
    } 
} 

這是由一個專家級的程序員幫助,但我仍然得到編譯器錯誤,這是bounceBall = ball.get(i);主要圍繞第(i)左右。

+0

共享編譯錯誤 – Shashank

回答

1

發生這種情況是因爲您有一個Object類型的對象列表,而不是BouncingBall對象列表,因此編譯器無法將對象轉換爲BouncingBall。 如果您使用的Java版本> = 1.5,使用類型列表: ArrayList<BouncingBall> ball, 或投對象BouncingBall:bounceBall = (BouncingBall)ball.get(i);

0

變化

ArrayList ball; 

ArrayList<BouncingBall> ball; 

將解決你的問題。

ArrayList默認爲ArrayList < Object>。因此,你會得到錯誤在線bounceBall = ball.get(i);因爲您正嘗試將Object分配給BouncingBall

相關問題