Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "VariableDeclaratorId expected after this token"

Tags:

java

class

I'm working on a little project for fun, that's essentially a little combat emulator. I'm trying to use a class similar to struct in C++, as in using it to create an object (in this case, a character or "entity", as the class is called). I'm getting the error in the title when attempting to call any integer in said class from the main function.

class entity{
    public int health;
    public int accuracy;
    public int power;
    public int defense;
}

And

public class Tutorial {
    static Random rnd = new Random();
    entity player;
    player.health = 100;  // Issue on the health part
    player.accuracy = 19; // Issue on the accuracy part
    player.power = 15;    // Issue on the power part
    player.defense = 18;  // I think you get it by now...

I've been looking around for a while to find some explanation, but there's none that I could find that explain the nature of the error as well as possible fixes for my situation. If I could get those, it would be wonderful.

like image 572
user2895469 Avatar asked Mar 24 '14 23:03

user2895469


2 Answers

The compiler is expecting a variable declaration on the line

player.health = 100; 

but is finding an assignment instead. The statements

Entity player = new Entity();
player.health = 100; 
player.accuracy = 19; 
player.power = 15; 
player.defense = 18; 

should be in a code block such as a method or constructor rather than the class block

like image 67
Reimeus Avatar answered Nov 15 '22 08:11

Reimeus


Procedural code cannot be written directly in a class definition. The code is causing syntax errors because it's not legal to do so.

Instead, put the code in an appropriate method or initialization block. (I do not think an initialization block is appropriate here, so I am trivially showing a "factory method".)

As such, consider an approach like

// This is a member variable declaration, which is why it's OK
// to have a (static) method call provide the value.
// Alternatively, player could also be initialized in the constructor.
Entity player = makeMeAPlayer();

static Entity makeMeAPlayer() {
    // Create and return entity; the code is inside a method
    Entity player = new Entity();
    player.health = 100;
    // etc.
    return player;
}

(I've also cleaned up the type to match Java Naming Conventions - follow suite!)

like image 37
user2864740 Avatar answered Nov 15 '22 10:11

user2864740