如何从静态方法访问我的私有变量

问题描述 投票:0回答:1

我有两个私有实例变量 xCord 和 yCord。我有一个名为 getSlope 的公共静态方法,它接受 Point 类的两个参数。当我尝试在它们上使用 .yCord 或 .xCord 时,它说不能从静态上下文引用非静态变量。

我尝试使用公共访问器方法来获取 x 和 y 坐标,但是当我尝试这样做时,我收到了相同的错误消息。在下面的代码片段中,我的目标是计算斜率,然后以句子格式打印出来,其中包括计算中涉及的各个坐标。我是编码新手,因此我的测试能力受到我所知道的限制。访问器方法位于底部。我还查看了已经回答的建议问题,但没有任何帮助。

private double xCord;
private  double yCord;

public static String getSlope(Point other) {
        double slope = ((Point.yCord - other.yCord) / (Point.xCord - other.xCord));
        return "The slope of the line from " + "(" + Point.xCord + ", " + Point.yCord + ")" + " to " + "(" + other.xCord + ", " + "(" + other.xCord + ", " + other.yCord + ")" +  "is " + slope;
}

public double getXCord() {return this.xCord;}
public double getYCord() {return this.yCord;}
java methods instance
1个回答
0
投票
  1. Point.yCord
    更改为
    this.yCord
    。 Point 是一个类,我认为你想要做的是使用 Point
    yCord
    的实例来减去一个新点
    yCord
  2. 您需要添加setter方法来设置点成员值。
  3. 删除
    static
    中的
    getSlope
  4. getSlope
    输出格式进行了一些修正。

示例代码

public class Point {
    private double xCord;
    private double yCord;
    public String getSlope(Point other) {
        double slope = ((this.yCord - other.yCord) / (this.xCord - other.xCord));
        return "The slope of the line from " + "(" + this.xCord + ", " + this.yCord + ")" + " to "  + "(" + other.xCord + ", " + other.yCord + ")" +  " is " + slope;
    }
    public double getXCord() {return this.xCord;}
    public void setXCord(double cord) {this.xCord=cord;}
    public double getYCord() {return this.yCord;}
    public void setYCord(double cord) {this.yCord=cord;}
}
  • 主要
    public static void main(String[] args)
    {
        Point point = new Point();
        point.setXCord(0);
        point.setXCord(0);
        Point newPoint = new Point();
        newPoint.setXCord(1.00);
        newPoint.setYCord(1.00);
        System.out.println(point.getSlope(newPoint));
    }
© www.soinside.com 2019 - 2024. All rights reserved.