<variable>无法解析为变量

时间:2016-05-03 15:28:10

标签: java

我有以下代码:

public interface CarInterface {

    int getCapacity();
    String getCarRegistration();
    void setCarRegistration(String registration);
    int getFuelAmmount();
    boolean isFull();
    boolean isRented();
    int addLitres(int litres);
    int drive();
}
public abstract class Car implements CarInterface{

    protected boolean full;
    private boolean rented;
    private String registration;
    protected int fuel;


    public String getCarRegistration() {
        return registration;
    }

    public void setCarRegistration(String registration){
        this.registration = registration;
    }


    public int getFuelAmmount() {
        return fuel;
    }

    public boolean isFull() {
        return full;
    }

    public boolean isRented() {
        return rented;
    }
}
public class LargeCar extends Car{

    public int drive() {
        return getFuelAmmount();
    }

    public int addLitres(int litres) {
        fuel = fuel + litres;
        if (fuel > 65) {
            fuel = 65;
        }
        if (isRented()) {
            int x = 5;
        }

        return x;


    }

    public int getCapacity() {
        return 65;
    }
}

Eclipse告诉我返回类型与接口声明不兼容(返回类型与。不兼容      CarInterface.addLitres(INT))。我不知道为什么会这样。我说我在界面中返回一个int,这就是我正在做的......

它还有“x&#39;”的问题,它说它无法解析为变量。奇怪的是,当我采取&#34; int x&#34;在if语句之外,错误消息消失。

3 个答案:

答案 0 :(得分:2)

您必须在x之外声明if

int x = 0;
if (isRented()) {
   x = 5;
}

答案 1 :(得分:0)

这里:

public int addLitres(int litres) {
        fuel = fuel + litres;
        if (fuel > 65) {
            fuel = 65;
        }
        if (isRented()) {
            int x = 5;
        }
        return x;
    }

无效,因为变量x在有限的范围内,只是因为在if段中声明...

改为:将int x声明为方法中的变量,并设置相应的值,如果燃料或你需要的任何东西

例如:

 public int addLitres(int litres) {
        int x = 0;
        fuel = fuel + litres;
        if (fuel > 65) {
            fuel = 65;
        }
        if (isRented()) {
            x = 5;
        }
        return x;
    }

答案 2 :(得分:0)

好吧,你不能返回x,因为它在if(isRented()){int x = 5}代码块中被声明,因此不在返回的范围内。要返回x,你必须在if(isRented()){int x = 5}范围之外定义它,如此

int x = 0;

if(isRented())
{
    x = 5;
}