[英]<Variable> Cannot Be Resolved to Variable
I have the following code:我有以下代码:
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 tells me that the return type is incompatible with the interface declaration (The return type is incompatible with CarInterface.addLitres(int)). Eclipse 告诉我返回类型与接口声明不兼容(返回类型与 CarInterface.addLitres(int) 不兼容)。 I have no idea why this is.
我不知道这是为什么。 I said I'd return an int in the interface, and that's what I'm doing...
我说我会在界面中返回一个 int ,这就是我正在做的......
It also has a problem with 'x', which it says cannot be resolved to a variable.它也有一个关于“x”的问题,它说它不能解析为一个变量。 Oddly enough, when I take "int x" out of the if statement, the error message disappears.
奇怪的是,当我从 if 语句中取出“int x”时,错误消息消失了。
You have to declare x
outside the if
.您必须在
if
之外声明x
。
int x = 0;
if (isRented()) {
x = 5;
}
This here:这里:
public int addLitres(int litres) {
fuel = fuel + litres;
if (fuel > 65) {
fuel = 65;
}
if (isRented()) {
int x = 5;
}
return x;
}
is invalid since the variable x is in a limited scope just because is declared inside a if segment...无效,因为变量 x 在有限的范围内仅仅因为在 if 段中声明...
do instead: declare the int x as a variable in the method and set its corresponding value if fuel or whatever you need to chec改为:将 int x 声明为方法中的变量并设置其对应的值(如果有燃料或任何您需要检查的内容)
public int addLitres(int litres) {
int x = 0;
fuel = fuel + litres;
if (fuel > 65) {
fuel = 65;
}
if (isRented()) {
x = 5;
}
return x;
}
Well, you can't return x because it's not in scope to be returned since it is declared inside of the if(isRented()){int x = 5} code block.好吧,你不能返回 x 因为它不在返回的范围内,因为它是在 if(isRented()){int x = 5} 代码块内声明的。 To return x you have to define it outside of the if(isRented()){int x = 5} scope like so
要返回 x 你必须像这样在 if(isRented()){int x = 5} 范围之外定义它
int x = 0;
if(isRented())
{
x = 5;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.