我试图创建一个具有基础对象的类。基础对象将用于创建一些对象,并且可以对抗'在另一个基于力量和通电的课程中。
在编译错误,无法访问的语句时,我遇到了这个错误。它指向第27行指向返回,有人可以帮助我吗?
public class Superhero {
private String superheroName;
private int superheroStrength;
public int powerUp;
public Superhero (String superheroName, int superheroStrength, int powerUp){
this.superheroName = superheroName;
this.superheroStrength = superheroStrength;
System.out.println("Superhero: " + superheroName);
System.out.println("Strength: " + ( superheroStrength + powerUp));
}
public Superhero (String superheroName, int powerUp){
this.superheroName = superheroName;
superheroStrength = 10;
System.out.println("Strength: " + ( superheroStrength+powerUp));
}
public int getStrength(){
return superheroStrength += powerUp;
}
public void powerUp (int powerUp){
this.powerUp += powerUp;
}
public Superhero battle(Superhero1 opponent){
if (this.getStrength()>opponent.getStrength());
return this;
return opponent;
}
public String toString(){
return this.superheroName;
}
}
答案 0 :(得分:1)
额外;
导致所有混乱
if (this.getStrength()>opponent.getStrength()); <--
那个分号终止了那里的陈述,并假设它是一个新的块,从那里开始。
因此代码
public Superhero battle(Superhero1 opponent){
if (this.getStrength()>opponent.getStrength());
return this;
return opponent;
}
等于
public Superhero battle(Superhero1 opponent){
if (this.getStrength()>opponent.getStrength()){
}
return this;
return opponent;
}
删除额外的;
(希望不是故意输入),代码就可以了。
正如有人已经评论过,这就是原因,请使用花括号来避免这样的情况。