2013-12-21 58 views
0

所以我有這個Polyline類使用另一個類(Point)來創建一個折線。Java:如何將Point值傳遞給Polyline?

Point只是定義了斧頭和y的值,並命名它(A點,B點等)

public class Polyline 

{ 
private Point [] corner; 

public Polyline() 
{ 
    this.corner = new Point[0]; 

} 

public Polyline (Point [] corner) 
{ 
    this.corner = new Point [cornerlength]; 
    for (int i = 0; i < corner.length; i++) 
     this.corner[i] = new Point (corner[i]); 

} 

現在的問題是,我怎麼給這些角及其值的點?我製作了一個名爲PolylineTest的程序,我想給它一些價值並打印出來,但我還沒有設法弄清楚如何去做。

我想這將是這樣的:

Polyline [] p1 = new Polyline[0]; 

,但我無法弄清楚如何給它的值。

任何人都可以給我一個正確的方向推動嗎?

預先感謝您

(代碼目前不編譯)

+2

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html –

+0

我試圖Polylinje [] P1 =新Polylinje [0]; \t \t p1 [0] = {「Point A」,3,4}; 但它說數組常量只能用作初始化程序 –

+0

是的,這是絕對沒有意義的。強烈建議閱讀文檔/教程。 –

回答

1

Asuming您Point類看起來是這樣的:

public class Point { 

    public String name; 
    public int x; 
    public int y; 

    public Point(String name, int x, int y) { 
     this.name = name; 
     this.x = x; 
     this.y = y; 
    } 

    public Point(Point p) { 
     this.name = p.name; 
     this.x = p.x; 
     this.y = p.y; 
    } 

    public String toString() { 
     return name + "[" + x + ", " + y + "]"; 
    } 
} 

,並添加這個方法將你Polyline類:

public String toString() { 
    return "Polyline " + Arrays.toString(corner); 
} 

的用法看起來像:

public class PolylineTest { 

    public static void main(String[] args) { 
     Point[] points = new Point[] { 
       new Point("A", 4, 2), 
       new Point("B", 8, 5), 
       new Point("C", 1, 7) 
     }; 
     Polyline polyline = new Polyline(points); 
     System.out.println(polyline); 
    } 
}