gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:18:35 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于java - 无法弄清楚在数组中使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com