【问题标题】:How do I call a function to all elements inside my ArrayList?如何对 ArrayList 中的所有元素调用函数?
【发布时间】:2019-08-11 04:53:23
【问题描述】:

我正在制作一个程序,该程序使用处理在屏幕上弹跳的球来绘制图案/设计。我设法得到一个球,移动、绘图和弹跳都正常。然而,一旦我创建了我的 ArrayList,并使用迭代器在屏幕上绘制了我所有的球,它们就停止了移动。

我不太确定该怎么做,我尝试在迭代器 while 循环中调用 move(),并尝试在 Ball() 的构造函数中调用它(不知道这是否有任何作用)。我只包含了我认为有问题的代码。

import java.util.ArrayList;
import java.util.Iterator;

class Ball {
    float x;
    float y;
    float directionDegree;
    float speed = 8;

    Ball() {
        x = random(0, 600);
        y = random(0, 600);
        directionDegree = random(60, 120);
    }

    void move() {
        x += speed * Math.cos(direction);
        y += speed * Math.sin(direction);
    }

    void drawAll(ArrayList<Ball> balls) {
        Iterator<Ball> iter = balls.iterator();

        while (iter.hasNext()) {
            iter.next().draw();
            move();
        }
    }
}

主类内部:

Ball b;
ArrayList<Ball> balls = new ArrayList<Ball>();
int amountOfBalls;

void setup() {
    size(600, 600);
    b = new Ball();
    amountOfBalls = 4;
    for (int i = 0; i < amountOfBalls; i++) {
        balls.add(new Ball());
    }
}

void draw() {
    b.drawAll(balls);
    b.contactWall();
    b.move();
}

我画的四个球就坐在那里,不动也不做任何古怪的动作,它们就坐在那里。

【问题讨论】:

    标签: java arraylist processing


    【解决方案1】:

    正如 BarSahar 所建议的,在 move 函数调用中没有 Ball 的引用。您也可以在while循环中执行以下代码

    Ball ball = iter.next(); ball.draw(); ball.move();

    但我建议您将 draw All 方法从 Ball 类中移出,并将其放在主类中。您可以直接从主类调用draw All。在 draw 所有你可以使用 foreach 循环进行迭代,并且可以调用 draw、move 和 connect`Wall。

    【讨论】:

      【解决方案2】:

      请注意,我是您的“while”循环,您只使用迭代器进行绘图。调用“move”方法时,该函数没有您要移动的特定球的引用。

      我的建议是:

      For (Ball ball : balls) {
          ball.move();
          ball.draw();
      }
      

      顺便说一下,主类中的draw函数不必要地使用了move方法(因为球已经在“move”中这样做了)。

      我还建议将“drawAll()”函数设为静态函数。由于它不对球“b”的单个实例进行操作,因此这是一种好习惯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-29
        • 2012-11-28
        • 2013-04-20
        • 1970-01-01
        • 2019-09-26
        • 2021-01-19
        • 2022-10-14
        • 2020-08-25
        相关资源
        最近更新 更多