Java - 赋值的左侧必须是变量
Java - The left-hand side of an assignment must be a variable
我正在尝试制作一个定位不同城市的小程序作为我的第一个 Java 项目。
我想从 class 'City' 访问我的 class 'GPS' 的变量,但我一直收到此错误:赋值的左侧必须是一个变量。任何人都可以向我解释我在这里做错了什么以及将来如何避免这样的错误?
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
}
(我想将变量保留为私有)
而这个class'Citiy'应该有坐标:
class City {
Gps where;
Location(int x, int y, int z) {
where.getX() = x;
where.getY() = y; //The Error Here
where.getZ() = z;
}
}
错误不言自明:您不能将值分配给不是字段或变量的内容。吸气剂用于 获取 存储在 class 中的值。 Java 使用 setters 处理存储值:
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
现在您可以通过调用 setter:
来设置值
City(int x, int y, int z) {
where.setX(x);
...
}
然而,这个解决方案并不理想,因为它使得 Gps
可变 。您可以通过添加构造函数来保持它不可变:
public Gps(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
现在City
可以一次性设置where
:
City(int x, int y, int z) {
where = new Gps(x, y, z);
}
不要使用 getter 设置属性。应该这样做:
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setZ(int z) {
this.z = z;
}
}
class City {
Gps where;
City(int x, int y, int z) {
this.where = new Gps();
where.setX(x);
where.setY(y);
where.setZ(z);
}
}
我正在尝试制作一个定位不同城市的小程序作为我的第一个 Java 项目。
我想从 class 'City' 访问我的 class 'GPS' 的变量,但我一直收到此错误:赋值的左侧必须是一个变量。任何人都可以向我解释我在这里做错了什么以及将来如何避免这样的错误?
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
}
(我想将变量保留为私有)
而这个class'Citiy'应该有坐标:
class City {
Gps where;
Location(int x, int y, int z) {
where.getX() = x;
where.getY() = y; //The Error Here
where.getZ() = z;
}
}
错误不言自明:您不能将值分配给不是字段或变量的内容。吸气剂用于 获取 存储在 class 中的值。 Java 使用 setters 处理存储值:
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
现在您可以通过调用 setter:
来设置值City(int x, int y, int z) {
where.setX(x);
...
}
然而,这个解决方案并不理想,因为它使得 Gps
可变 。您可以通过添加构造函数来保持它不可变:
public Gps(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
现在City
可以一次性设置where
:
City(int x, int y, int z) {
where = new Gps(x, y, z);
}
不要使用 getter 设置属性。应该这样做:
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setZ(int z) {
this.z = z;
}
}
class City {
Gps where;
City(int x, int y, int z) {
this.where = new Gps();
where.setX(x);
where.setY(y);
where.setZ(z);
}
}