简体   繁体   中英

java <identifier> expected when initializing variables

I wanted to do a little Farming game and started to write classes for resources and crops. But when i initialize my resource at the beginning it gives me an identifier expected error.By the way dont mind the German comments. :D

public class HarvestinaNutshell extends JFrame {
  // Anfang Attribute
  public final Resource itemWheat; 
  public final Resource itemBarley; 
  // Ende Attribute

  public HarvestinaNutshell(String title) { 
    // Frame-Initialisierung
    super(title);
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    int frameWidth = 300; 
    int frameHeight = 300;
    setSize(frameWidth, frameHeight);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - getSize().width) / 2;
    int y = (d.height - getSize().height) / 2;
    setLocation(x, y);
    setResizable(false);
    Container cp = getContentPane();
    cp.setLayout(null);
    // Anfang Komponenten

    // Ende Komponenten

    setVisible(true);
  } // end of public HarvestinaNutshell

  // Anfang Methoden
  itemWheat = new Resource(1,"Wheat",true,100);
  itemBarley = new Resource(1,"Barley",true,120);
  // Ende Methoden

  public static void main(String[] args) {
    new HarvestinaNutshell("HarvestinaNutshell");
  } // end of main

} // end of class HarvestinaNutshell

at itemWheat = new Resource(1,"Wheat",true,100); i get an error behind the itemWheat that says identifier expected and i couldnt find a reason to it.

Your itemWheat is declared at he beginning as final so it has to be initialised there or inside constructor.

private final itemWheat = new ...

In this case it will be even simpler than having it inside costructor, because if later you decide to add more ctors and call one inside the other you will have to manage init of finals.

Those two assignments are outside the constructor, where you can only have field declaration code.

Move them up a few lines so they appear before the line

} // end of public HarvestinaNutshell

In java Everything should be in Methods. The lines responsible for error are outside the constructor add them in the constructor and you are good to go.

public HarvestinaNutshell(String title) { 
// Frame-Initialisierung
super(title);


 ....

// Anfang Methoden
itemWheat = new Resource(1,"Wheat",true,100);
itemBarley = new Resource(1,"Barley",true,120);
// Ende Methoden

  setVisible(true);
} // end of public HarvestinaNutshell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM