gpt4 book ai didi

java - 将值传递给类

转载 作者:行者123 更新时间:2023-12-02 05:01:35 25 4
gpt4 key购买 nike

我正在尝试使用 java.awt.Point 将 x 和 y 坐标传递给类中的构造函数。我的主类抛出一个错误,说“构造函数四边形(int,int,int,int,int,int,int,int)未定义。我在传递给构造函数时想到'公共(public)四边形(点...点)'我可以将坐标作为一个简单的列表传递。有人可以告诉我这几行代码可能出了问题吗?

主要

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

}

最佳答案

你的代码根本没有意义,你有 varargs Points 参数,但没有在构造函数中使用它们,如果你不需要输入参数,你可以用无参数构造函数替换它

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

如果您确实想将参数作为可变参数传递和使用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);

关于java - 将值传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28230377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com