我對如何從自定義類中提取數據感到困惑。該代碼將笛卡爾座標組織在一個名爲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'對象的方法 - 使用它們。 –
感謝您的反饋,我剛剛閱讀了駱駝案例爲什麼在編碼方面很重要 - 我對這種風格很陌生,可以看到這方面的好處。至於當你說「使用它們」時 - 這正是我試圖解決的問題,現在它已經解決了。再次感謝你的時間。 –