正在练习与Java中的构造师一起工作,这是我试图编译的类:
import java.util.*;
import java.lang.*;
public class mob{
public Map enemies = new HashMap<String, Point>();
public Point pn = new Point(1, 1);
enemies.put("Peon", pn);
public Point gn = new Point(5, 2);
enemies.put("Goblin", gn);
public Point tl = new Point(25, 8);
enemies.put("Troll", tl);
public Point oc = new Point(13, 5);
enemies.put("Orc", oc);
public String name;
public int hp;
public int dmg;
public mob(String type){
name=type;
hp=enemies.get(type).getX();
dmg=enemies.get(type).getY();
}
public mob(){
name="Peon";
hp=enemies.get("Peon").getX();
dmg=enemies.get("Peon").getY();
}
void setName(String name){
this.name=name;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in());
System.out.System.out.println("Enter mob type:");
String type = scan.nextln();
if(mob.containsKey(type)){
mob mob1 = new mob(type);
}
else{
mob mob1 = new mob();
mob1.setName(type);
}
System.out.println("You just spawned a "+mob1.name+", it has "+mob1.hp+" hp and "+mob1.dmg+" dmg!");
}
}
主要方法旨在从控制台中获取一些输入,并使用映射("敌人")或默认MOB根据输入而创建特定的MOB。但是,当我尝试在命令提示符中编译此命令时,我会在所有敌人中获取错误。put()方法,即:
mob.java:7: error: <identifier> expected
enemies.put("Peon", pn);
^
mob.java:7: error: illegal start of type
enemies.put("Peon", pn);
^
mob.java:9: error: <identifier> expected
enemies.put("Goblin", gn);
^
等。
研究了类似的问题,并试图解决问题(因此所有公开声明),但无法弄清楚这一点...
使用Java和Javac是V11.0.2
钻石在那里告诉编译器通用类。但是,语法应为:
public Map<String,Point> enemies = new HashMap<>();
和默认的 the enemies.put("Peon", pn);
命令必须发生在构造函数中。
java中的语句必须使用一种方法。看来您正在尝试使用enemies.put("Goblin", gn);
之类的语句初始化字段,因此我建议您为每个字段创建一个初始化方法。您的代码将变成:
import java.util.*;
import java.lang.*;
public class mob{
public Map enemies = initialiseEnemies();
public Point pn = new Point(1, 1);
public Point gn = new Point(5, 2);
public Point tl = new Point(25, 8);
public Point oc = new Point(13, 5);
public String name;
public int hp;
public int dmg;
public static Map initialiseEnemies() {
// Build the Hashmap here and return it.
}
public mob(String type){
name=type;
hp=enemies.get(type).getX();
dmg=enemies.get(type).getY();
}
public mob(){
name="Peon";
hp=enemies.get("Peon").getX();
dmg=enemies.get("Peon").getY();
}
void setName(String name){
this.name=name;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in());
System.out.System.out.println("Enter mob type:");
String type = scan.nextln();
if(mob.containsKey(type)){
mob mob1 = new mob(type);
}
else{
mob mob1 = new mob();
mob1.setName(type);
}
System.out.println("You just spawned a "+mob1.name+", it has "+mob1.hp+" hp and "+mob1.dmg+" dmg!");
}
}