在java中用向量和点创建一个矩形?

时间:2009-12-01 20:37:56

标签: java

我被赋予了一个创建一个定义2个点的类的作业。然后创建一个定义向量的类。然后创建一个定义矩形的类(4个向量)。在此任务之前,我被赋予了创建点和向量类以计算向量长度的任务。我在该作业上有100%的分数,所以我知道我可以使用该代码来帮助我创建这个矩形类。

在当前的赋值中,任务是创建一个矩形类,然后计算其周长和面积。我花了一段时间创建我的矩形类,但每当我觉得它看起来很完美时,就会引发一堆编译错误。

无论如何这是我之前的代码,我用来帮助我处理矩形类:

点类:

public class Point {

private double x;
private double y;

public Point(){
x=0.0;
y=0.0;
}
public Point(double a, double b){
x=a;
y=b;
}
public double getX(){return x;}
public double getY(){return y;}
}

Vector class:

public class Vector {

private Point p = new Point();
private Point q = new Point();


public Vector(Point a, Point b){
p=a;
q=b;
}
public double giveLength ( ){
double xDiff=q.getX() - p.getX();
double yDiff=q.getY() - p.getY();
return Math.sqrt( (xDiff*xDiff)+(yDiff*yDiff) );
}

public double giveLength2(){
double x2Diff = p.getX2() - q.getX2();
double y2Diff = p.getY2() - q.getY2();
return Math.sqrt( (x2Diff*x2Diff)+(y2Diff*y2Diff) );
}
}

Assignment7 class:

import java.util.*;
import java.math.*;
import java.io.*;

class Assignment7 {
public static void main(String[] args)throws Exception{ 

double X1;
double Y1; 
double X2;
double Y2;

Point P1;
Point P2;
Vector V;

Scanner in = new Scanner(System.in);
System.out.println("Please enter a filename:"); 
String filename = in.nextLine(); 

File inputFile = new File(filename);
Scanner reader = new Scanner(inputFile);    


while ( reader.hasNext()){

X1 = reader.nextDouble();
Y1 = reader.nextDouble();
P1 = new Point(X1,Y1);


X2 = reader.nextDouble();
Y2 = reader.nextDouble();
P2 = new Point(X2,Y2);


V = new Vector ( P1, P2 );

System.out.println("X1 " + X1 + " length is " + V.giveLength() );

} 
}
}

输入文件的格式为:

x y
x y
x y

下面是我当前的矩形类看起来像但它抛出了许多构造函数错误。

class Rectangle{

private Vector w = new Vector();
private Vector x = new Vector();
private Vector y = new Vector();
private Vector z = new Vector();

public Rectangle(Vector a, Vector b, Vector c, Vector d){
w=a;
x=b;
y=c;
z=d;
}

public double givePerimeter(){
    double perimeter = ((w.giveLength() + x.giveLength2())* 2);
    return perimeter;
}

public double giveArea(){
    double area = (w.giveLength() * y.giveLength2());
    return area;
}


}

感谢您提前帮助!

1 个答案:

答案 0 :(得分:2)

您尝试在此处初始化4个向量:

private Vector w = new Vector();
private Vector x = new Vector();
private Vector y = new Vector();
private Vector z = new Vector();

但是你没有没有参数的Vector构造函数!

尝试构建没有点的向量是没有意义的。你想要做的是首先在坐标系中读取并设置你的4个点,然后在你的点被定义后从点(嗯,每个2个)构造4个向量。

所以...将这些private声明移到已经设置了点的位置下方,并在每组括号中加入一对点。