[英]I don't know what's wrong
if(handler.obj.isEmpty())
handler.addObject(new Box(x, y, ID.Box));
else{
for(int i = 0; i < handler.obj.size(); i++){
Object tempObj = handler.obj.get(i);
if (tempObj.getX() == x && tempObj.getY() == y && tempObj.getId() == ID.Box)
handler.removeObect(tempObj);
else
handler.addObject(new Box(x, y, ID.Box));
}
}
the handler.addObject()
in the else
statement seems unreachable or doesn't work else
语句中的handler.addObject()
似乎无法访问或不起作用
From comment:来自评论:
public class Handler {
LinkedList<Object> obj = new LinkedList<Object>();
public void tick(){
for (int i = 0; i < obj.size();i++){
Object tempObj = obj.get(i);
tempObj.tick();
}
}
public void render(Graphics g){
for (int i = 0; i < obj.size(); i++){
Object tempObj = obj.get(i);
tempObj.render(g);
}
}
public void addObject(Object obj){
this.obj.add(obj);
}
public void removeObect(Object obj){
this.obj.remove(obj);
}
}
Let's see.让我们来看看。 Assume first time it runs,
x,y
is 1,1
.假设它第一次运行时,
x,y
是1,1
。 So you add Box(1,1)
.所以你添加
Box(1,1)
。
Next time is run, let's assume x,y
is 2,3
.下次运行时,假设
x,y
是2,3
。 So, enter for
loop:因此,进入
for
循环:
i = 0
: Not same x,y
, so enter else
, and add Box(2,3)
. i = 0
:不相同的x,y
,所以输入else
,并添加Box(2,3)
。i = 1
: Same as x,y
(yeah, we just added it), so enter if
and remove Box(2,3)
. i = 1
:与x,y
相同(是的,我们刚刚添加了它),因此输入if
并删除Box(2,3)
。 Result: Box added and removed again.结果:再次添加和删除框。
Oh yeah, a debugger would have told you the same thing.哦,是的,调试器会告诉你同样的事情。
Your problem is that your for
loop ends in the wrong place.你的问题是你的
for
循环在错误的地方结束。 This causes two undesirable symptoms.这会导致两种不良症状。
Box
once for every element in your list that doesn't match the box, instead of adding it just once.Box
一次列表中的所有元素不匹配的盒子,而不是将它添加一次。Box
objects that you just added, once you get to the end of the loop.Box
对象。 I would recommend rewriting the method like this.我建议像这样重写方法。 Notice how the
for
loop ends before the new object is added - this makes sure that the object is added at most once.请注意
for
循环如何在添加新对象之前结束 - 这确保最多添加一次对象。 Also notice the return
statement after an object is removed - this can be done because once the object is removed, the method has no more work to do.还要注意删除对象后的
return
语句 - 可以这样做,因为一旦删除了对象,该方法就没有更多工作要做。
public void addOrRemoveBox(int x, int y) {
for(int i = 0; i < handler.obj.size(); i++){
Object tempObj = handler.obj.get(i);
if (tempObj.getX() == x && tempObj.getY() == y && tempObj.getId() == ID.Box) {
handler.removeObect(tempObj);
return;
}
}
handler.addObject(new Box(x, y, ID.Box));
}
Lastly, you appear to have written your own class called Object
(otherwise this code wouldn't compile).最后,您似乎编写了自己的名为
Object
的类(否则此代码将无法编译)。 This is probably a bad idea, because it will cause you to get confused between your Object
class, and the Object
class that's built into Java.这可能是一个坏主意,因为它会导致你得到你的困惑与
Object
类和Object
是内置到Java类。 I suggest you rename that class.我建议你重命名那个类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.