-5

How can I use or replace the code down below using for-Loop to draw size (25 * 25) rectangles in Java?

if (drawRectangles == 1) {
    graphics.fillRect(430, 428, 25, 25);
}

if (drawRectangles == 2) {graphics.fillRect(430, 428, 25, 25);
    graphics.fillRect(460, 428, 25, 25);
}

if (drawRectangles == 3) {
    graphics.fillRect(430, 428, 25, 25);
    graphics.fillRect(460, 428, 25, 25);
    graphics.fillRect(490, 428, 25, 25);
}

if (drawRectangles == 4) {
    graphics.fillRect(430, 428, 25, 25);
    graphics.fillRect(460, 428, 25, 25);
    graphics.fillRect(490, 428, 25, 25);
    graphics.fillRect(520, 428, 25, 25);
}

1 Answers1

2

for comprehensions are an integral part of many languages.

Tutorial for Java: docs.oracle.com/../tutorial/../for

Look for regular increments, loops are ideal for this.

You increment your x by 30 each time.

for(int inc = 0; inc  < drawRectangles; inc ++){
    x = 430 + (30 * inc)
    ...
    graphics.fillRect(x, y, x_size, y_size);
}

Consider using variables for things that are static. It makes your code more intuitive and makes it far easier to update and maintain.