Question

This is probably the most obvious question on stackoverflow. Please Help! What is wrong with this code?

public class LevelOne extends Move {
    static int block1x = 3;
    static int block1y = 1;
    static int block2x = 3;
    static int block2y = 2;
    static int block3x = 3;
    static int block3y = 3;
    block1x *= 32;
    block1y *= 32;
    block2x *= 32;
    block2y *= 32;
    block3x *= 32;
    block3y *= 32;
}

On line 7 it says it expected { instead of ; On line 14 it actually says it expected } to complete classbody. Why???

Was it helpful?

Solution

There is nothing wrong with doing this:

public class LevelOne extends Move {
    static int block1x = 3*32;
    static int block1y = 1*32;
    static int block2x = 3*32;
    static int block2y = 2*32;
    static int block3x = 3*32;
    static int block3y = 3*32;
}

The actual values 96, 32, 64, etc. will be computed at compile time. You're probably better off defining a static final int multipier = 32 constant, so that each of your fields would be defined as static int block1x = 3 * multiplier and so on. Your code will be easier to read and more maintainable.

That should be ok because those are static fields. For the general case with non-static fields, this part should be inside a method or a constructor of your class:

block1x *= 32;
block1y *= 32;
block2x *= 32;
block2y *= 32;
block3x *= 32;
block3y *= 32;

Right now they are in the class declaration, where we can define fields, methods and constructors (among other things). That space is used to define what the class has. To define specific code, use methods or constructors.

OTHER TIPS

The initialization part should be in a static section or in a static method:

public class LevelOne extends Move {
    static int block1x = 3;
    static int block1y = 1;
    static int block2x = 3;
    static int block2y = 2;
    static int block3x = 3;
    static int block3y = 3;

    // will be called right after the static variables are initialized
    static{
        block1x *= 32;
        block1y *= 32;
        block2x *= 32;
        block2y *= 32;
        block3x *= 32;
        block3y *= 32;
    }
}

or you could declare these fields as instance fields (same as above, just remove the static word).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top