Aramza Aramza - 1 year ago 106
Java Question

Java: Loop increment not starting at 0

I've checked out other resources and haven't been able to find something helpful. But I'm attempting to figure out how to start loop increment at 0 instead of 1 for drawing the number inside the oval as shown below.

I'd appreciate the help.

My code: (Drawing Panel:

// Draws boxed ovals using a for loop.

import java.awt.*;

public class DrawLoopFor
public static void main(String[] args)
DrawingPanel panel = new DrawingPanel(501, 251);

Graphics g = panel.getGraphics();
int sizeX = 50;
int sizeY = 25;

for (int i = 0; i < 11; i++)
int cornerX = i*50;
int cornerY = i*25;

g.fillOval(cornerX + 5, cornerY + 5, sizeX-10, sizeY-10);
g.drawString("" + i, cornerX - 28, cornerY - 8);
g.drawRect(cornerX, cornerY, sizeX, sizeY);

My output (wrong):
My incorrect output

Correct output:
Correct output

Answer Source

You're drawing the text in the previous box rather than the current box. That's why the last box is empty, and the zero is drawn outside the visible screen.

Most likely because you subtract 28 from cornerX when you draw.

Try adding rather than subtracting. As I don't have your DrawingPanel class I can't confirm the exact offsets to cornerX and cornerY that you need, but I think you should use something like:

g.drawString("" + i, cornerX + 22, cornerY + 17);

(22 for the X coordinate, since you were drawing the start of the text 3 pixels before the middle of the box, and 25 - 3 = 22; 17 for the Y coordinate because the height is 25, and you were previously drawing the baseline of the text 8 higher than the end of the box, so 25 - 8 = 17)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download