【问题标题】:Java - The left-hand side of an assignment must be a variableJava - 赋值的左侧必须是变量
【发布时间】:2017-05-08 18:58:54
【问题描述】:

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

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

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

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

class City {
  Gps where;

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

【问题讨论】:

  • ints 是私人的。创建设置器:setX(int x) {this.x = x;} 然后使用 where.setX(x); 另外,你的类无论如何都不会编译
  • 您需要使用 Setter 来更改 Gps 的私有成员。

标签: java getter-setter


【解决方案1】:

错误不言自明:您不能将值分配给不是字段或变量的东西。 Getter 用于获取类中存储的值。 Java 使用 setter 来处理将值存储回来:

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);
}

【讨论】:

  • 这对我有用。感谢您的帮助。请问最后一个问题,如果我想通过 City 内部的 Getter 调用 GPS 的 x 怎么办? :)
  • @Baldr 您可以通过通常的方式访问 getter - 例如public int getX() {return where.getX();} 另一种方法是发布 where - 例如public Gps getWhere() {return where;} 调用者会得到这样的 X:myCity.getWhere().getX()
【解决方案2】:

不要使用 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);
    }
}

【讨论】:

    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多