无法弄清楚在数组中使用循环

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


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]);

}


慕森卡
浏览 73回答 1
1回答

狐的传说

您所要做的就是在连续点之间画线。点的下一个索引i是i+1。%对于最后一个点,它是 0。这可以通过模 ( ) 运算符 (h )来实现(i+1) % points.size()。获取循环中的 2 个连续点并在它们之间画一条线: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);       }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java