如何解决java中与用户定义的方法和对象相关的以下错误?

ehxuflar  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(285)

我编写了以下java代码:

public class Point2D{
    private double xc, yc;

    public Point2D(double x, double y){
            this.xc = x;
            this.yc = y;
        }

    public Point2D createNewPoint(int xOff, int yOff){
        this.xc = xc + xOff;
        this.yc = yc + yOff;
        return xc;  
    }

    public static void main(String[] args){
        Point2D p1 = new Point2D(2.5, 3.5);

        Point2D p3 = p1.createNewPoint(5, -2);
        System.out.println(p3);
    }
}

我收到以下错误:

Point2D.java:27: error: incompatible types: double cannot be converted to Point2D
        return xc;  
               ^
1 error

有没有人能帮我解决这个错误,以及如何从java中的用户定义方法返回两个变量/值?

kupeojn6

kupeojn61#

返回值的类型应与返回类型匹配。你回来了 xc 属于, double 但返回类型是 Point2D .
代替

public Point2D createNewPoint(int xOff, int yOff){
    this.xc = xc + xOff;
    this.yc = yc + yOff;
    return xc;  
}

具有

public Point2D createNewPoint(int xOff, int yOff) {
    return new Point2D(xc + xOff, yc + yOff);  
}

另外,创建一个 toString 实现如下所示的内容,以便在打印对象时可以获得有意义的输出 Point2D .

public class Point2D {
    private double xc, yc;

    public Point2D(double x, double y) {
        this.xc = x;
        this.yc = y;
    }

    public Point2D createNewPoint(int xOff, int yOff) {
        return new Point2D(xc + xOff, yc + yOff);
    }

    @Override
    public String toString() {
        return "Point2D [xc=" + xc + ", yc=" + yc + "]";
    }

    public static void main(String[] args) {
        Point2D p1 = new Point2D(2.5, 3.5);

        Point2D p3 = p1.createNewPoint(5, -2);
        System.out.println(p3);
    }
}
p5cysglq

p5cysglq2#

为私有字段添加getter
如果需要新对象,请从createnewpoint方法返回一个新对象,如下面的解决方案所示
使用getter方法访问各个值。

class Point2D {
 private double xc, yc;

 public Point2D(double x, double y){
         this.xc = x;
         this.yc = y;
     }

 public Point2D createNewPoint(int xOff, int yOff){
     return new Point2D(this.xc + xOff, this.yc + yOff);  
 }

 public double getXc() {
     return xc;
 }

 public double getYc() {
     return yc;
 }

 public static void main(String[] args){
     Point2D p1 = new Point2D(2.5, 3.5);

     Point2D p3 = p1.createNewPoint(5, -2);
     System.out.println (p3.getXc() + ":" + p3.getYc());
 }

}

相关问题