开发者

unexpected behavior in printing string in loop

开发者 https://www.devze.com 2022-12-22 19:02 出处:网络
I don\'t understand why this is happening: I have an integer being passed to a label object: int NTURNS = 3;

I don't understand why this is happening:

I have an integer being passed to a label object:

int NTURNS = 3;     
for (int i = NTURNS; i > 0; i--){
printTurns(i);  
buildBall(); 
}

and printTurns is this:

private void printTurns(int i){

 GLabel turns = new GLabel("" + i);
     remove(turns);     
 add(turns, (WIDTH - PADDLE_WIDTH), (BRICK_Y_OFFSET / 2));          
}

This will print the number of turns left in the game at the top. I have the remove(turns); there to remove the text so the next text won't overlap the old, but this is开发者_运维技巧 not working for some reason.

The numbers are stacking on top of eachother. Why is that?


You've got a bit of a GLabel problem going on there. You're creating a new GLabel for each iteration through the loop.

You should create a single GLabel, add it to the form, and then call GLabel.setLabel() to change the text for each iteration of the loop. That should save you some headaches down the road.

Somewhere in your application's form initialization (maybe constructor?):

public class MyForm : GCanvas
{
    private GLabel _turns = new GLabel();

    public MyForm()
    {
        add(_turns);
    }

    private void printTurns(int i)
    {
        _turns.setLabel("" + i);
        _turns.setLocation(WIDTH - PADDLE_WIDTH), (BRICK_Y_OFFSET / 2));
    }
}


You're removeing the new string -- which isn't there yet -- not the old one! I.e., the second time around you're removeing "2" -- but there is no such string (as the first time you had added "3", not "2"!), so there's no effect. You need to remember the previous string you added, if any, e.g. in a private member variable, and remove that one string before you add the new one!


I had a hard time wrapping my head around Justin Niessner's answer, because I'm still new to constructors...however it did lead me to a method that worked for me. I'm putting my answer in, but I will mark his answer as correct:

private void setupGame(){

    GLabel turns = new GLabel("");   
    add(turns, (WIDTH - PADDLE_WIDTH), (BRICK_Y_OFFSET / 2));
    for (int i = NTURNS; i > 0; i--){
    turns.setLabel("" + i); 

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号