0
我有一个方法processInput
当它是用户的转向时被激活,变量prompt
让我知道用户在游戏的哪个点。事件驱动的基于回合的文本游戏,创建一个对象
所以我有一个提示“找到一个有价值的对手新闻F”。如果用户按下“F”,我会生成一个对象,然后随机让用户/对手互相攻击。之后,当用户再次转向时,它会提示“按A攻击”,但由于前一个提示(if
)创建了一个对象,编译器不知道它是否被执行以允许我引用该对象。
在processInput
的最后一个if子句中,行player.attack(e);
,e
可能尚未初始化,因此我不知道如何解决此问题。
public class inputListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
String inputLog = input.getText();
input.setText("");
console.append(input + "\n");
processInput(inputLog);
}
void processInput(String inputLog){
input.setEnabled(false);
Enemy e;
if(prompt.startsWith("What is your name")){
if(inputLog.isEmpty()){
player.setName("Bob");
console.append("...\nYour name therefore is Bob");
}else{
player.setName(inputLog);
console.append("Alright "+player.getName()+"...\n");
}
choosePath();
}else if(prompt.startsWith("If you wish to find a worthy opponent")){
if(inputLog.equalsIgnoreCase("f")){
e = generateEnemy();
console.setText("");
console.append(e.getClass().getSimpleName()+" Level: "+e.getLvl());
console.append("\nHP: "+e.getHP());
console.append("\n\n\n");
if(Math.random()>0.49){
userTurn("Press A to attack");
}else{
e.attack(player);
if(!player.isDead()){
userTurn("Press A to attack");
}
}
}
}else if(prompt.startsWith("Press A to attack")){
player.attack(e);
if(!player.isDead()||!e.isDead()){
e.attack(player);
userTurn("Press A to attack");
}else if(e.isDead()){
console.append("\nYou have killed "+e.getClass().getSimpleName()+"!\n\n");
choosePath();
}
}
}
}
e!= null要求我在processinput状态的开始时敌人e = null;这将永远把它变为空,并摧毁我的对象。我提示用户输入的方式void userTurn(String prompt){console.append(this.prompt = prompt); input.setEnabled(true); input.requestFocus(); } – Higeath
检查null不应该要求您将其设置为null。你已经在上面声明它,所以它被初始化为null。 – pmcevoy12
它确实显示了'变量e可能未被初始化' – Higeath