为什么我的 Java 代码会出现编译错误“; expected”?

Why is there the compile error, " ; expected " for my Java Code?

我真的不明白为什么 "Map<String, Integer> buildTable(){".
的括号后会出现这个编译错误 这是我正在处理的代码:我已经定义了城市 class。

import java.util.Map;
import java.util.HashMap;

public class CityMap{

public static void main(String[] args){  
  String _city;
  Map<String, Integer> cityTable = buildTable();

  Map<String, Integer> buildTable(){
     String aCity;
     Map<String, Command> result = new HashMap<String, Command>();

     aCity = new City();
     result.put("NYC", 100000);


     aCity = new City();
     result.put("Boston", 500);

      return result;
 }

我是初学者,欢迎大家多多指教

您不能在其他方法内部声明方法。

将您的 buildTable 方法移到 main 方法之外(然后您必须使其成为 static 或创建一个对象实例以从 main 调用它).

buildTable 的方法声明需要在 main 的方法声明之外。

即,

   import java.util.Map;
   import java.util.HashMap;

public class CityMap{

public static void main(String[] args)
{  
  String _city;
  Map<String, Integer> cityTable = buildTable();
}

public static Map<String, Integer> buildTable(){
 String aCity;
 Map<String, Command> result = new HashMap<String, Command>();

 aCity = new City();
 result.put("NYC", 100000);


 aCity = new City();
 result.put("Boston", 500);

  return result;
  }
}

public static void main(String[] args){} 毕竟是一种方法。因此,您不能在其中声明另一个方法。

此外,当您 return 结果时,您的编译器会感到困惑,因为虽然它是为您的 buildTable() 方法设计的,但它被放置在您的 main() 方法中。

解决方案:

public static void main(String[] args){  
  String _city;
  Map<String, Integer> cityTable = buildTable();
}

Map<String, Integer> buildTable(){
 String aCity;
 Map<String, Command> result = new HashMap<String, Command>();

 aCity = new City();
 result.put("NYC", 100000);

 aCity = new City();
 result.put("Boston", 500);

 return result;
}
import java.util.Map;
import java.util.HashMap;
public class CityMap {
    static Map < String, Integer > buildTable() {
        Map < String, Integer > result = new HashMap < String, Integer > ();
        result.put("NYC", 100000);
        result.put("Boston", 500);
        return result;
    }
    public static void main(String[] args) {
        Map < String, Integer > cityTable = buildTable();
    }
}

命令未定义,创建实例变量不使用它们根本不会做任何事情,方法不能在方法内部声明;仅在 class 内部 - 您可以在方法内部声明 class(内部 class)和在 class.

内部的方法