Java “VariableDeclaratorId expected after this token”

二次信任 提交于 2020-01-30 05:23:22

问题


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.


回答1:


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




回答2:


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!)



来源:https://stackoverflow.com/questions/22622676/java-variabledeclaratorid-expected-after-this-token

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!