Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Why won't my for-loop generate a shape repeatedly?

I'm writing a program that creates a thermometer, and I want to make it so that the thermometer slowly fills up until it reaches the right temperature. To accomplish this, I've created a for loop that adds a red rectangle over and over again. This is the code:

public void drawTherm() { GRect colorRed = new GRect(THERM_WIDTH, 30); colorRed.setFilled(true); colorRed.setColor(Color.red); for(int i=0; i<THERM_OVAL; i++){ add(colorRed, 353, 400-(i*3));
pause(1000); } }

The problem is that instead of adding multiple GRects, it only adds a single one and then moves that single GRect up the thermometer stem. Does anyone have any ideas as to why it won't create multiple shapes?

1 Answer

Instead of adding multiple rectangles, could you add one rectangle, but in your loop increase the height of the one rectangle?

Something like this:

public void drawTherm() { 

    GRect colorRed = new GRect(THERM_WIDTH, 30); 
    colorRed.setFilled(true); 
    colorRed.setColor(Color.red); 

    add(colorRed, 353, 400);

    for(int i=0; i<THERM_OVAL; i++) { 
        colorRed.adjustHeight(i); //new method...see below
        pause(1000); 
    }
}

public void adjustHeight(int newHeight) {
    this.height += newHeight;
}

That's brilliant! I'll give it a shot.

Glad to help! I hope it works!

I just realized the adjusteHeight method won't increase by 1 the way I wrote it. It should look like this:

public void adjustHeight(int newHeight) {
    this.height = newHeight;
}