尝试获取名为 DrawGraphics 的自定义类来包含自定义对象的 ArrayList,而不是单个 Sprite。然而 ArrayList 拒绝接受新的 Bouncer 对象,当它接受时,DrawGraphics 类的其余部分无法识别它。
原始代码
package objectssequel;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Graphics;
public class DrawGraphics {
Bouncer movingSprite; //this was the original single sprite
/** Initializes this class for drawing. */
public DrawGraphics() {
Rectangle box = new Rectangle(15, 20, Color.RED);
movingSprite = new Bouncer(100, 170, box);
movingSprite.setMovementVector(3, 1);
}
/** Draw the contents of the window on surface. */
public void draw(Graphics surface) {
movingSprite.draw(surface);
}
}
尝试的解决方案: 首先,我创建了 Bouncer 类对象的 ArrayList
ArrayList<Bouncer> bouncerList = new ArrayList<Bouncer>();
一切都好。我首先在下面的行中插入以下代码
bouncerList.add(movingSprite);
这会生成“标记上的语法错误,构造错误”和“标记“movingSprite”上的语法错误,此标记后预期的 VariableDeclaratorId”编译器错误。我猜这可能是因为我在方法体之外使用了bouncerList.add(),所以我为类DrawGraphics创建了以下方法
public void addBouncer(Bouncer newBouncer) {
bouncerList.add(newBouncer);
}
然后我在 DrawGraphics() 中调用此方法:
addBouncer(movingSprite);
编译器错误告诉我 movingSprite 无法解析为变量类型。我尝试这样做:
public void addBouncer() {
Bouncer movingSprite;
bouncerList.add(movingSprite);
}
然后尝试通过给它一个空设置来初始化 movingSprite,但也没有这样的运气,可能还有十几种其他组合方法来解决这个问题。有什么解决办法吗?如何在 DrawGraphics 类中创建 Bouncer 对象的 ArrayList?
编辑:是否可以不使用并从原始代码中删除“Bouncer movingSprite”,并仅从ouncerList.add()创建对象的实例?
最佳答案
在此代码中
public void addBouncer(Bouncer newBouncer) {
bouncerList.add(Bouncer); // this is trying to add a class
}
您需要更改为
public void addBouncer(Bouncer newBouncer) {
bouncerList.add(newBouncer); // this will add the object
}
及之后
movingSprite.setMovementVector(3, 1);
通话
addBouncer (movingSprite);
关于java - ArrayList无法解析变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22343798/