2016-12-04 8 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

これは、BouncingBallオブジェクトのリストではなくObject型のオブジェクトのリストがあるために発生します。そのため、コンパイラはオブジェクトをBouncingBallに変換することはできません。 ArrayList<BouncingBall> ball、 またはキャストオブジェクトBouncingBallへ:あなたはJavaのバージョン> = 1.5、使用型付けされたリストを使用する場合 はbounceBall = (BouncingBall)ball.get(i);

0

変更を

ArrayList ball; 

ArrayList<BouncingBall> ball; 

にあなたの問題を解決します。

ArrayListはデフォルトでArrayList <オブジェクト>です。したがって、あなたは行bounceBall = ball.get(i)にエラーが発生します。 ObjectBouncingBallを割り当てようとしているので、

関連する問題