2016-02-19 26 views
0

我已经将几个随机绘制的线的坐标存储在对象数组中。 我现在想能够以编程方式处理数组中所有对象的x1。我无法弄清楚如何做到这一点,甚至不知道如何查看存储行的坐标。如果我做println()我只是得到对象的内存引用。如何访问作为数组中对象存储的形状的坐标

这里是到目前为止的代码:

class Line{ 
    public float x1, y1, x2, y2; 

    public Line(float x1, float y1, float x2, float y2){ 
     this.x1 = x1; 
     this.y1 = y1; 
     this.x2 = x2; 
     this.y2 = y2; 
    } 

    public void draw(){ 
     line(x1, y1, x2, y2); 
     float rot = random(360); 
     rotate(rot); 
    } 

    //public boolean intersects(Line other){ 
    // //left as exercise for reader 
    //} 
} 

ArrayList<Line> lines = new ArrayList<Line>(); 

void setup(){ 
    background(204); 
    size(600, 600); 

    for(int i = 0; i < 20; i++){ 
     float r = random(500); 
     float s = random(500); 
     lines.add(new Line(r,s,r+10,s+10)); 


printArray(lines); 
for(Line line : lines){ 
     line.draw(); 

    } 
} 
} 

回答

1

只需用点号。用你的线类,你可以创建一个使用new关键字和构造函数(即具有相同的名称作为类的特殊功能)的Line对象(或实例):

Line aLine = new Lines(0,100,200,300); 

一旦你有一个实例,你可以访问它的使用实例名称变量(称为属性),那么.符号,然后在变量名:

println("aLine's x1 is " + aLine.x1); 

在你的示例代码,在draw()功能您访问.draw()函数(称为方法)的每个Line实例:

for(Line line : lines){ 
     line.draw(); 

    } 
} 

这只是一个使用同样的理念,接入线路的其他成员的之事:

for(Line line : lines){ 
     //wiggle first point's x coordinate a little (read/write x1 property) 
     line.x1 = random(line.x1 - 3,line.x1 + 3); 
     line.draw(); 

    } 
} 

请务必仔细阅读Daniel Shiffman's Objects tutorial了解更多详情。

相关问题