This site requires JavaScript, please enable it in your browser!
Greenfoot back
hhh
hhh wrote ...

2020/4/6

I NEED HELP

hhh hhh

2020/4/6

#
Im trying to run a code but its saying illegal start of exspression this is the bit thats messing up: int y; = getY(); int x; = getX(); can i have help thanks
Kostya20052011 Kostya20052011

2020/4/6

#
int y = getY(); int x = getX(); First, without ";" . Secondly, I always declare variables, and then work with them, so do it better like this: int x; int y; x=getX(); y=getY();
Super_Hippo Super_Hippo

2020/4/6

#
Yes to first. No to second. Unless you need to do it.
Kostya20052011 Kostya20052011

2020/4/6

#
I forgot to say that variables are declared before methods, and are used in the method itself, is this an error?
danpost danpost

2020/4/6

#
Kostya20052011 wrote...
I forgot to say that variables are declared before methods, and are used in the method itself, is this an error?
It's not an error. It is just not always necessary. If the variables are assigned new values and only used within the method during the current act step, then it is probably best to declare them within the method. Also, if the variable is only used one in the method, it might be best to use the method call to get the value at the time it is needed and forego declaring a variable for it at all. So, with this:
int x;
int y;
java.util.List actorsBelow;

public void doSomething()
{
    x = getX();
    y = getY();
    actorsBelow = getWorld().getObjectsAt(x, y+60, Actor.class);
    for (Object obj : actorsBelow)
    {
        // work with actors in list
    }
}
, the variables retain their values and are kept by the instance of this class ("this") permanently. The following is a bit better:
public void doSomething()
{
    int x = getX();
    int y = getY();
    java.util.List actorsBelow;
    actorsBelow = getWorld().getObjectsAt(x, y+60, Actor.class);
    for (Object obj : actorsBelow)
    {
        // work with actors in list
    }
}
The variables become obsolete at the end of the method and new variables are created on the following call to the method. However, it is bulky and somewhat hard to follow. Better yet, might be this:
public void doSomething()
{
    for (Object obj : getWorld().getObjectsAt(getX(), getY()+60, Actor.class))
    {
        // work with actors in list
    }
}
where the method calls are used exactly where needed. The 2nd and 3rd sets of code may run identically; but the 3rd set is easier to follow.
You need to login to post a reply.