将值传递给类

时间:2015-01-30 06:28:42

标签: java awt

我试图使用java.awt.Point将x和y坐标传递给类中的构造函数。我的主要类是抛出错误说"构造函数Quadrilateral(int,int,int,int,int,int,int,int)是未定义的。当我转到我的构造函数公共四边形(点......点)时,我想到了#39;我可以将坐标作为简单列表传递。有人能告诉我这几行代码可能出错吗?

主要

import java.awt.Point;


    public class QuadrilateralTest
    {
        public static void main(String[] args)
        {
            Quadrilateral quadrilateral = new Quadrilateral(1, 1, 6, 2, 6, 9, 2, 7);
System.out.printf("%s %s %s %s %s\n", quadrilateral);
        }
    }

四边形课程

import java.awt.Point;


public class Quadrilateral
{
    //points contain x and y coordinates
    private Point point1;
    private Point point2;
    private Point point3;
    private Point point4;


    public Quadrilateral(Point... points)
    {
        point1 = new Point(1, 2);
        point2 = new Point(3, 4);
        point3 = new Point(5, 6);
        point4 = new Point(7, 8);       
    }

    //setters and getters
    public Point getPoint1()
    {
        return point1;
    }

    public Point getPoint2()
    {
        return point2;
    }

    public Point getPoint3()
    {
        return point3;
    }

    public Point getPoint4()
    {
        return point4;
    }

    public String toString()
    {
         return ("\nThe Points of the Quadrilateral are:\n " +
                getPoint1() +"," + getPoint2() +"," + getPoint3() + "," + getPoint4())+"\n";
    }

}

3 个答案:

答案 0 :(得分:1)

你的构造函数接收varargs Point - 你不能只传入一堆int。尝试实例化Point并传入它们。

答案 1 :(得分:1)

您的代码完全没有意义,您有varargs Points参数,但在构造函数中没有使用它们,如果您没有使用输入参数,可以用no-arg构造函数替换它

 public Quadrilateral()
    {
        point1 = new Point(1, 2);
        point2 = new Point(3, 4);
        point3 = new Point(5, 6);
        point4 = new Point(7, 8);       
    }

并在main()

中执行
Quadrilateral quadrilateral = new Quadrilateral();

如果你真的想要传递和使用参数作为varargs Point,那么让你的构造函数使用参数的值: -

public Quadrilateral(Point... points){

if((points.length>0)&&(points[0]!=null)){ //make sure to check this condition to allow user to input any number of parameters
point1=points[0];
}

if((points.length>1)&&(points[1]!=null)){
point2=points[1];
}
.
.
}

然后你可以写main(): -

Point point1 =new Point(1,2);
Point point2 =new Point(1,2);
Quadrilateral quad=new Quadrilateral(point1,point2);

答案 2 :(得分:0)

您的代码可以修改为@Evan建议,如下所示:

public Quadrilateral(Point... points)
{
    point1 = points[0];
    point2 = points[1];
    point3 = points[2];
    point4 = points[3];       
}

但是你可以理解会有很多问题。

如果您在构造函数中看到正好需要4个点,则根本不应该使用varargs。您应该只获得4个不同的Point参数。

public Quadrilateral(Point _point1, Point _point2, Point _point3, Point _point4)
{
    point1 = _point1;
    point2 = _point2;
    point3 = _point3;
    point4 = _point4;       
}

这样你就会强迫用户发送4 Point个。{/ p>