无法弄清楚使用数组内部的循环

时间:2019-11-01 00:06:48

标签: java processing

在我的作业中,有一个术语是2个节点之间,前一次单击的节点应保留在屏幕上,并且应该有将每个节点与下一个节点相连的行(最后一个节点与第一个节点相连)。除了这些行(当然还有网格线)之外,应该没有其他行。我尝试通过使用数组内部的循环来做到这一点。但这不是我正在寻找的答案。...

int [] a;
int [] b;
ArrayList<Point> points = new ArrayList<Point>();

class Point {
    int x, y, r;

    Point(int x, int y, int r) {
        this.x = x;
        this.y = y;
        this.r = r;
    }

    void Draw() {
        circle(this.x, this.y, this.r*2);
    }
}

int n_part=10;
void setup(){
    size(600,360);

    a = new int [100];
    b = new int [100];
}

void draw () {

    background (255);

    int gridW = width/n_part;
    int gridH = height/n_part;

    stroke(210);
    noFill();
    for (int row = 0; row < n_part; row++){ 
        int gridY = 0 + row*gridH;
        for (int col = 0; col < n_part; col++) {
            int gridX = 0+ col* gridW;
            rect (gridX, gridY, gridW, gridH);   
        }
    }

    stroke(0, 0, 0);
    fill(0);
    for (int i = 0; i < points.size(); ++ i) {
        Point p = points.get(i);
        p.Draw();
    }
}

void mousePressed() {
    int gridW = width/n_part;
    int gridH = height/n_part;

    int x = round(mouseX / (float)gridW) * gridW;
    int y = round(mouseY / (float)gridH) * gridH;

    points.add(new Point(x, y, 5));
    {
    for (int j=0; j < a.length; j++) 
        a [j] = (mouseX / (int)gridW) * gridW;
    for (int k=0; k < b.length; k++) 
        b [k] = height;
    }
}

void mouseReleased(){
    for (int k=0; k < a.length; k++) 
        line (0, 0, a [k], b [k]);
}

1 个答案:

答案 0 :(得分:0)

您要做的就是在连续点之间画线。

i的下一个索引是i+1。最后一点是0。这可以通过模(%)运算符(h (i+1) % points.size())来实现。

获取一个循环中的两个连续点,并在它们之间画一条线:

for (int i = 0; i < points.size(); ++ i) {
    Point p1 = points.get(i);
    Point p2 = points.get((i+1) % points.size());
    line(p1.x, p1.y, p2.x, p2.y);   
}

请参见示例:

void draw () {

    background (255);

    int gridW = width/n_part;
    int gridH = height/n_part;

    strokeWeight(1);
    stroke(210);
    noFill();
    for (int row = 0; row < n_part; row++){ 
        int gridY = 0 + row*gridH;
        for (int col = 0; col < n_part; col++) {
            int gridX = 0+ col* gridW;
            rect (gridX, gridY, gridW, gridH);   
        }
    }

    stroke(0, 0, 0);
    fill(0);
    for (int i = 0; i < points.size(); ++ i) {
        Point p = points.get(i);
        p.Draw();
    }

    strokeWeight(3);
    stroke(255, 0, 0);
    for (int i = 0; i < points.size(); ++ i) {
        Point p1 = points.get(i);
        Point p2 = points.get((i+1) % points.size());
        line(p1.x, p1.y, p2.x, p2.y);   
    }
}