在下面的代码中,一旦执行,它将根据随机数生成器更改对象diet
的状态hek
。我还有一个undo()
函数,它在运行时完全正常。
我要做的是:当对象的状态发生变化但前一状态prevDiet
等于更改后的状态currentDiet
时,我希望程序调用{{1 }}
undo()
但是,只要前一个状态import java.util.Random;
import javax.swing.JOptionPane;
public class changeDietCom implements Command {
Hek hek;
Random rand = new Random();
int x;
DietBehaviour prevDiet;
DietBehaviour currentDiet;
public changeDietCom(Hek hek) {
this.hek = hek;
}
public void execute() {
x = rand.nextInt(3) + 1;
prevDiet = hek.getDietBehaviour();
if (x == 1) {
hek.setDietBehaviour(new Enemies());
JOptionPane.showMessageDialog(null, "Hek's diet has been changed!", "Changing diet", JOptionPane.INFORMATION_MESSAGE);
currentDiet = hek.getDietBehaviour();
hek.performDiet();
if (prevDiet == currentDiet) {
JOptionPane.showMessageDialog(null, "Diet hasn't changed!", "Current Diet = Prev Diet", JOptionPane.INFORMATION_MESSAGE);
undo();
}
}
else if (x == 2) {
hek.setDietBehaviour(new ArmouredKnights());
JOptionPane.showMessageDialog(null, "Hek's diet has been changed!", "Changing diet", JOptionPane.INFORMATION_MESSAGE);
currentDiet = hek.getDietBehaviour();
hek.performDiet();
if (prevDiet == currentDiet) {
JOptionPane.showMessageDialog(null, "Diet hasn't changed!", "Current Diet = Prev Diet", JOptionPane.INFORMATION_MESSAGE);
undo();
}
}
else if (x == 3) {
hek.setDietBehaviour(new BigMac());
JOptionPane.showMessageDialog(null, "Hek's diet has been changed!", "Changing diet", JOptionPane.INFORMATION_MESSAGE);
currentDiet = hek.getDietBehaviour();
hek.performDiet();
if (prevDiet == currentDiet) {
JOptionPane.showMessageDialog(null, "Diet hasn't changed!", "Current Diet = Prev Diet", JOptionPane.INFORMATION_MESSAGE);
undo();
}
}
}
public void undo() {
JOptionPane.showMessageDialog(null, "Undoing diet change...", "Undoing Diet Change", JOptionPane.INFORMATION_MESSAGE);
hek.setDietBehaviour(prevDiet);
hek.performDiet();
}
}
和当前状态prevDiet
在运行时彼此相等,currentDiet
语句就不会返回true,我可以& #39;不知道为什么不呢?请问有人可以解释为什么以及如何解决这个问题?
我应该提一下,我正在使用命令模式来设计这部分程序。
答案 0 :(得分:1)
DietBehavior
个对象是对象类型,因此您无法使用==
来比较它们。您要使用的是.equals()
。如果DietBehavior
是您自己的类,那么您将必须实现该方法,但它非常简单。
public boolean equals(Object other) {
// compare them here based on instance variables
}
答案 1 :(得分:1)
使用if (prevDiet == currentDiet) {
,您可以比较对象引用而不是实际值。请改用if (prevDiet.equals(currentDiet)) {
,并确保覆盖equals()
的{{1}}方法。
请注意,当您覆盖DietBehaviour
时,您还应该覆盖equals()
,并且实现应该是一致的。有关此内容的更多信息,请访问here。