dimanche 17 novembre 2019

Why does my variable don't "remember" the changes in the if-Statement?

I got a problem with my code: My program is going to draw a few specific rectangles. Therefore I use a loop to calculate repetitive the size of my new rectangles.

    int c = readInt("Counter: ");
    double width1 = readDouble("Width: ");
    for (int i = 0; i <= c; i++) {

        double height1;
        double lastwidth;
        double lastheight;
        double topleftx;
        double toplefty;


        if ((i == 1) && (i != 0)) {
            topleftx = 0;
            toplefty = 0;
            height1 = width1 / 1.618;
            GRect rect = new GRect(topleftx, toplefty, width1, height1);
            add(rect);
            lastwidth = width1;
            lastheight = height1;
        }
        ;

        if ((i == 2) || ((i - 2) % 4 == 0) && (i != 0)) {
            height1 = lastheight;
            width1 = height1 / 1.618;
            toplefty = toplefty;
            topleftx = topleftx + lastwidth - width1;
            GRect rect = new GRect(topleftx, toplefty, width1, height1);
            add(rect);
            lastwidth = width1;
            lastheight = height1;
        }
    }

But I get some error messages like that one: The local variable lastheight may not have been initialized. in the line: height1 = lastheight; of the second loop. But I have already initialized my variable in the first loop. So it's like my variable forgot the value I gave to it in the first loop...?!

But why? And how can i fix this?

Thanks for your help. :)

Aucun commentaire:

Enregistrer un commentaire