用循环创建对象,但仍然可以在循环外部访问它们?

huangapple go评论67阅读模式
英文:

Creating objects with a loop and still can access them outside the loop?

问题

我是Java和面向对象编程的初学者。
我正在创建一个“带有粒子的盒子”的模拟器。以下是程序中所需的内容:

  1. 一个具有固定宽度和高度的盒子,图案为“-”和“|”。
  2. 具有x、y位置的粒子(0 <= x <= 宽度;0 <= y <= 高度)。符号:*。
  3. 8个方向的枚举方向。
  4. 将所有粒子随机移动一次,并在它们中的任何粒子发生碰撞(位置相同)时创建一个新粒子。

我一直在努力找到答案,即如何使用循环创建随机数量的粒子,并且在循环外仍然可以对它们进行操作?因为我希望每个创建的粒子在迭代后保留下来,以便进行进一步的move()执行。是否有这种类型访问的任何语法?

以下是我尝试过的内容,有时会输出2个、3个粒子,有时则不会输出:

public Box() {
    particle = new Particle();
    for (int i = 0; i <= HEIGHT + 1; i++) {
        for (int j = 0; j <= WIDTH + 1; j++) {

            if (i == 0 || i == HEIGHT + 1 && i != particle.getY()){
                System.out.print("-");
            } else {
                if (j == particle.getX() && i == particle.getY()) {
                    System.out.print("*");
                } else if (j == 0 || j == WIDTH + 1 && j != particle.getX()) {
                    System.out.print("|");
                } else if (i != 0 && i != HEIGHT + 1) {
                    System.out.print(" ");
                }
            }
        }

        System.out.println("");

    }
}
英文:

I am a beginner in Java as well as OOP.
I am creating a simulator of "a box with particles". Here's what required in the program:

  1. A box with fixed WIDTH & HEIGHT with the pattern of "-" and " | "
  2. Particles with x, y position (0 <= x <= WIDTH; 0 <= y <= HEIGHT). Symbol: *
  3. Enum Direction of 8 directions
  4. move() all particles in random direction and create a new particle if any of them collide (same position)

What I've been strugging to find the answer is that how can I create random number of particles with a loop and can still work on them outside the loop? Because I want each created particle remain after an iteration for further move() execution. Is there any syntax for this kind of access?

Here's what I've tried as this sometimes output 2, 3 particles, sometimes none:

public Box() {
    particle = new Particle();
    for (int i = 0; i &lt;= HEIGHT + 1; i++) {
        for (int j = 0; j &lt;= WIDTH + 1; j++) {

            if (i == 0 || i == HEIGHT + 1 &amp;&amp; i != particle.getY()){
                System.out.print(&quot;-&quot;);
            } else {
                if (j == particle.getX() &amp;&amp; i == particle.getY()) {
                    System.out.print(&quot;*&quot;);
                } else if (j == 0 || j == WIDTH + 1 &amp;&amp; j != particle.getX()) {
                    System.out.print(&quot;|&quot;);
                } else if (i != 0 &amp;&amp; i != HEIGHT + 1) {
                    System.out.print(&quot; &quot;);
                }
            }
        }

        System.out.println(&quot;&quot;);

    }
    
}

答案1

得分: 0

编码会变得更容易,如果你将大任务分解为小任务。

我将粒子的创建与粒子的显示分开。这样,我可以一次只专注于任务的一部分。

这是我生成的输出。

|------------------|
|            *     |
|                  |
|  *   * *      *  |
|    *       *     |
|        * *       |
|  * * *      *    |
|      *           |
|           * *    |
|------------------|

我所做的只是生成初始条件。移动粒子并检查碰撞的任务留给你来完成。我假设一旦特定的粒子向南移动,例如,它会一直向南移动,直到撞到另一个粒子或墙壁。撞到墙壁会改变方向为北。

我的 Eclipse 生成了 Particle 类的 hashCodeequals 方法。这些方法对于 Setcontains 方法很重要。我使用了一个 Set,以确保没有重复的粒子。因为粒子是随机生成的,模拟中可能不会有所有的“最大”粒子。

generateParticles 方法中,我获得一个介于 1 和 WIDTH - 1 之间(包括两端)的随机数 w,以及一个介于 1 和 HEIGHT - 1 之间的随机数 h。这确保了所有创建的粒子都在“盒子”内部。

以下是完整的可运行示例代码。

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class ParticleSimulator {

    public static void main(String[] args) {
        ParticleSimulator ps = new ParticleSimulator();
        ps.displaySimulation();
    }

    private static int WIDTH = 20;
    private static int HEIGHT = 10;

    private Random random;

    private Set<Particle> particles;

    public ParticleSimulator() {
        this.random = new Random();
        this.particles = generateParticles(20);
    }

    private Set<Particle> generateParticles(int maximum) {
        Set<Particle> particles = new HashSet<>();
        for (int i = 0; i < maximum; i++) {
            int x = random.nextInt(WIDTH - 1) + 1;
            int y = random.nextInt(HEIGHT - 1) + 1;
            Particle particle = createParticle(x, y);
            particles.add(particle);
        }
        return particles;
    }

    public void displaySimulation() {
        for (int h = 0; h < HEIGHT; h++) {
            for (int w = 0; w < WIDTH; w++) {
                if (w == 0 || w == (WIDTH - 1)) {
                    System.out.print('|');
                    continue;
                }

                if (h == 0 || h == (HEIGHT - 1)) {
                    System.out.print('-');
                    continue;
                }

                Particle particle = createParticle(w, h);
                if (particles.contains(particle)) {
                    System.out.print('*');
                } else {
                    System.out.print(' ');
                }
            }
            System.out.println();
        }
    }

    private Particle createParticle(int x, int y) {
        Particle particle = new Particle();
        particle.setX(x);
        particle.setY(y);
        return particle;
    }

    public class Particle {

        private int x;
        private int y;

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result +
                     getEnclosingInstance().hashCode();
            result = prime * result + x;
            result = prime * result + y;
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Particle other = (Particle) obj;
            if (!getEnclosingInstance().equals(
                    other.getEnclosingInstance()))
                return false;
            if (x != other.x)
                return false;
            if (y != other.y)
                return false;
            return true;
        }

        private ParticleSimulator getEnclosingInstance() {
            return ParticleSimulator.this;
        }

    }

}
英文:

Coding is easier if you break the large task into smaller tasks.

I separated the creation of the particles from the display of the particles. That way, I could focus on one part of the task at a time.

Here's the output I generated.

|------------------|
|            *     |
|                  |
|  *   * *      *  |
|    *       *     |
|        * *       |
|  * * *      *    |
|      *           |
|           * *    |
|------------------|

All I did was generate the initial condition. I'm leaving it up to you to move the particles and check for collisions. I'm assuming that once a particular particle moves south, as an example, it continues south until it hits another particle or the wall. Hitting the wall would change the direction to north.

My Eclipse generated the hashCode and equals methods of the Particle class. These methods are essential for the Set contains method to work. I used a Set so there would be no duplicate particles. Because the particles are generated randomly, there might not be all maximum particles in the simulation.

In the generateParticles method, I get a random w between 1 and WIDTH - 1, inclusive, and a random h between 1 and HEIGHT -1, inclusive. This ensures that all particles created are inside the "box".

Here's the complete runnable example code.

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class ParticleSimulator {
public static void main(String[] args) {
ParticleSimulator ps = new ParticleSimulator();
ps.displaySimulation();
}
private static int WIDTH = 20;
private static int HEIGHT = 10;
private Random random;
private Set&lt;Particle&gt; particles;
public ParticleSimulator() {
this.random = new Random();
this.particles = generateParticles(20);
}
private Set&lt;Particle&gt; generateParticles(int maximum) {
Set&lt;Particle&gt; particles = new HashSet&lt;&gt;();
for (int i = 0; i &lt; maximum; i++) {
int x = random.nextInt(WIDTH - 1) + 1;
int y = random.nextInt(HEIGHT - 1) + 1;
Particle particle = createParticle(x, y);
particles.add(particle);
}
return particles;
}
public void displaySimulation() {
for (int h = 0; h &lt; HEIGHT; h++) {
for (int w = 0; w &lt; WIDTH; w++) {
if (w == 0 || w == (WIDTH - 1)) {
System.out.print(&#39;|&#39;);
continue;
}
if (h == 0 || h == (HEIGHT - 1)) {
System.out.print(&#39;-&#39;);
continue;
}
Particle particle = createParticle(w, h);
if (particles.contains(particle)) {
System.out.print(&#39;*&#39;);
} else {
System.out.print(&#39; &#39;);
}
}
System.out.println();
}
}
private Particle createParticle(int x, int y) {
Particle particle = new Particle();
particle.setX(x);
particle.setY(y);
return particle;
}
public class Particle {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + 
getEnclosingInstance().hashCode();
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Particle other = (Particle) obj;
if (!getEnclosingInstance().equals(
other.getEnclosingInstance()))
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
private ParticleSimulator getEnclosingInstance() {
return ParticleSimulator.this;
}
}
}

huangapple
  • 本文由 发表于 2020年10月18日 23:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64414960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定