I'm new to java and I am trying to write a code that generates 10 random boxes then removes one box and adds another. Thus the total remains 10 boxes, but the loop keeps going. I have figured out how to create the 10 random boxes, but I am unsure how to remove one from that. here is the code:

final int width = 800;
        final int height = 600;
        final int boxWidth = 50;
        final int maxBoxes = 10;

        this.setSize(width, height);
            Random random = new Random();

                for(int box=0;box<maxBoxes;box++)
                {
                    int x = random.nextInt(width-boxWidth);
                    int y = random.nextInt(height-boxWidth);
                    GRect r = new GRect(x, y, boxWidth, boxWidth);
                    Color c = new Color(random.nextInt(256),
                                        random.nextInt(256), random.nextInt(256));
                    r.setFilled(true);
                    r.setFillColor(c);
                    this.add(r);

                    this.pause(100);
有帮助吗?

解决方案

You need to store the box values in an array. Then in each iteration of your loop erase the screen and redraw all 10 boxes. Then randomly replace the box values for one box and repeat.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top