首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java -赋值的左侧必须是变量

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

Stack Overflow用户
提问于 2017-05-09 02:58:55
回答 2查看 11.4K关注 0票数 1

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

我想从类'City‘访问我的类'GPS’的变量,但我总是得到这个错误:赋值的左边必须是一个变量。任何人都可以向我解释我在这里做错了什么,以及如何在未来避免这样的错误?

代码语言:javascript
复制
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; 
   }
}

(我希望将变量保留为私有)

这个类'Citiy‘应该有坐标:

代码语言:javascript
复制
class City {
  Gps where;

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-09 03:02:51

错误不言而喻:您不能为不是字段或变量的对象赋值。Getter用于获取存储在类中的值。Java使用setter来处理存储值的问题:

代码语言:javascript
复制
public int getX() {
    return x; 
}
public void setX(int x) {
    this.x = x;
}

现在,您可以通过调用setter来设置值:

代码语言:javascript
复制
City(int x, int y, int z) {
    where.setX(x);
    ...
}

然而,这种解决方案并不理想,因为它使Gps变得可变。您可以通过添加构造函数使其保持不可变:

代码语言:javascript
复制
public Gps(int x, int y, int z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

现在City可以一次设置where

代码语言:javascript
复制
City(int x, int y, int z) {
    where = new Gps(x, y, z);
}
票数 2
EN

Stack Overflow用户

发布于 2017-05-09 03:04:08

不要使用getter设置属性。应该这样做:

代码语言:javascript
复制
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);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43855307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档