我对如何从自定义类中提取数据感到困惑。该代码将笛卡尔坐标组织在一个名为linesegment
的类中,其中几个类CartesianCoordinate
作为其成员。我被困在试图找到两组笛卡尔坐标之间的距离。在java中操作类
我该如何解码linesegment
类,进入cartesiancoordinate
类,然后访问单个的double
值从主类打印到屏幕?
下面是我的程序中使用的三类:
主类:
public class lab3
{
public static void main(String [] args)
{
cartesiancoordinate one, two; //instantsiating one and two as type cartesiancoordiante
one = new cartesiancoordinate(5, 6); //putting the information for one and two into type cartesiancoordinate
two = new cartesiancoordinate(4.5, -6.5);
linesegment oneandtwo;
oneandtwo = new linesegment(one, two);
System.out.println(one.toString()); //dual X/Y statements using a toString method
System.out.println(two.toString());
System.out.println(oneandtwo.tostring());
System.out.println("X for one is: " + one.getx()); //individual X/Y statements using getter methods
System.out.println("Y for one is: " + one.gety());
System.out.println("X for two is: " + two.getx()); //individual X/Y statements using getter methods
System.out.println("Y for two is: " + two.gety());
double tester;
oneandtwo.test();
System.out.println("The test method returned the distance between the two cartesian coordinates to be: " + tester);
}
}
的cartesiancoordinate类:
class cartesiancoordinate
{
private double xposition;
private double yposition;
public cartesiancoordinate(double x, double y)
{
this.xposition = x;
this.yposition = y;
}
public double getx()
{
return this.xposition;
}
public double gety()
{
return this.yposition;
}
public String toString()
{
return "(" + this.xposition + "/" + this.yposition + ")";
}
}
的麻烦线段类:
class linesegment
{
private cartesiancoordinate startpoint, endpoint, s1, e1;
public cartesiancoordinate one, two;
public linesegment(cartesiancoordinate x, cartesiancoordinate y)
{
this.startpoint = x;
this.endpoint = y;
}
public cartesiancoordinate getstartpoint()
{
return this.startpoint;
}
public cartesiancoordinate getendpoint()
{
return this.endpoint;
}
public String tostring()
{
return ("The start point is " + this.startpoint + " and the end point is " + this.endpoint);
}
public double test()
{
double x1,x2,y1,y2;
cartesiancoordinate s1,e1;
getstartpoint() = s1;
getendpoint() = e1 ;
s1.getx() = x1;
s1.gety() = y1;
e1.getx() = x2;
e1.gety() = y2;
double tester;
tester = x1 + x2 + y1 + y2;
return tester;
}
}
关于代码质量的备注:阅读关于java代码风格指南;你的方法和类的名字很简单......完全“错误”。除此之外,你的命名也是“不好的”(从无用的意义上说):一种方法应该说明它在做什么。那么,什么是**测试**测试?为什么它会返回一个double?最后:考虑转向JUnit单元测试;而不是从静态主要方法手动“测试”。 – GhostCat
没有什么特别区分你写的类(“自定义类”)与标准库中提供的类有关如何操作它们并从中提取数据。你的'cartesiancoordinate'类提供了提取单个坐标的方法 - 使用它们。你的'linesegment'类提供了获得代表起点和终点的'cartesiancoordinate'对象的方法 - 使用它们。 –
感谢您的反馈,我刚刚阅读了骆驼案例为什么在编码方面很重要 - 我对这种风格很陌生,可以看到这方面的好处。至于当你说“使用它们”时 - 这正是我试图解决的问题,现在它已经解决了。再次感谢你的时间。 –