-1

Im trying to create a class that has a base object. The base object will be used to create a few objects and be made to 'fight' in another class based on strength and powerups.

I have got this error when compiling 'Error, unreachable statement' and it points to line 27 pointing to the return, can someone help me out please?

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;
    }
}
4

1 回答 1

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;
}

删除那个额外的;希望不是故意输入的),代码就可以了。

正如有人已经评论过的那样,这就是原因,总是使用花括号来避免这种情况。

于 2015-10-16T13:11:01.177 回答