gpt4 book ai didi

Java - 赋值的左侧必须是变量

转载 作者:行者123 更新时间:2023-11-29 08:36:23 24 4
gpt4 key购买 nike

我正在尝试制作一个定位不同城市的小程序作为我的第一个 Java 项目。

我想从“城市”类访问我的“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;
}
}

(我想将变量保留为私有(private))

这个类“Citiy”应该有坐标:

class City {
Gps where;

Location(int x, int y, int z) {
where.getX() = x;
where.getY() = y; //The Error Here
where.getZ() = z;
}
}

最佳答案

错误不言而喻:您不能将值赋给不是字段或变量的东西。 Getters 用于获取 存储在类中的值。 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);
}

关于Java - 赋值的左侧必须是变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43855307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com