【问题标题】:Incompatible types error in Command Prompt命令提示符中的不兼容类型错误
【发布时间】:2020-07-20 22:19:12
【问题描述】:

我有一项关于计算两点之间距离的工作。它由点类、线类和主类组成。以下是我的点课。在处理私有双距离(点 p)方法后,我无法在公共双 getDistance(点 p)方法中返回 p。我在命令提示符上运行代码,它显示错误:不兼容的类型:点不能转换为双精度。请指教。

class Point
{
    private int x;
    private int y;

//Constructor
public Point()
{
    //nothing
}

//Second constructor
public Point (int x, int y)
{
    this.x = x;
    this.y = y;
}

//Copy constructor
public Point (Point p)
{
    this (p.x, p.y);
}

private double distance(Point p)
{
    int dX = this.x - p.x;
    int dY = this.y - p.y;
    double result = Math.sqrt(dX * dX + dY * dY);
    return result;
}

public double getDistance(Point p)
{        
    return p;
}

//getter
public int getX()
{
    return x;
}

public int getY()
{
    return y;
}

//setter
public void set(int x, int y)
{
    this.x = x;
    this.y = y;
}

public String toString ()
{
    return String.format ("Given Point (%d, %d)", x, y);
}

}

【问题讨论】:

    标签: java class command-prompt composition composite


    【解决方案1】:

    您将对象 Point p 作为参数并将其作为双精度值返回。

    在您的代码块中,您声明的是对象点 p 的返回,而不是双精度数据类型。

    public double getDistance(Point p) {
       return p; 
    }
    

    如果您只是想计算对象的距离,请使用distance() 方法。此方法已返回计算为double 的距离。

    private double distance(Point p) {
        int dX = this.x - p.x;
        int dY = this.y - p.y;
        double result = Math.sqrt(dX * dX + dY * dY);
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2013-09-23
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多