【问题标题】:Creating objects with a loop and still can access them outside the loop?使用循环创建对象并且仍然可以在循环外访问它们?
【发布时间】:2020-10-18 15:18:17
【问题描述】:

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

  1. 具有固定宽度和高度的盒子,带有“-”和“|”的图案
  2. x、y 位置的粒子(0
  3. 8个方向的枚举方向
  4. move() 随机方向的所有粒子,如果其中任何一个发生碰撞(相同位置),则创建一个新粒子

我一直在努力寻找答案是,我怎样才能用循环创建随机数量的粒子,并且仍然可以在循环外对它们进行处理?因为我希望每个创建的粒子在迭代后保留以进一步执行 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("");

    }
    
}

【问题讨论】:

    标签: java class oop object


    【解决方案1】:

    如果您将大型任务分解为较小的任务,则编码会更容易。

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

    这是我生成的输出。

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

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

    我的 Eclipse 生成了 Particle 类的 hashCodeequals 方法。这些方法对于Set contains 方法的工作是必不可少的。我使用了Set,所以不会有重复的粒子。因为粒子是随机生成的,所以模拟中可能不会有所有maximum粒子。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多