2015-03-03 53 views
0

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

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; 
} 

我是初学者,所以任何解释都是值得欢迎的。

+4

您不能在其他方法中声明方法。 – Thilo 2015-03-03 02:35:49

回答

0

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

I.E.,

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; 
    } 
} 
4

您不能在其他方法中声明方法。

移动你buildTable方法main方法之外(然后你必须要么使其static或创建一个对象实例从main称呼它)。

0

公共静态无效的主要(字串[] args){}是一种方法,毕竟。出于这个原因,你不能在其中声明另一个方法。另外,当你返回结果时你的编译器会感到困惑,因为尽管它是用于你的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; 
} 
0
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(); 
    } 
} 

命令没有定义,创建实例变量不使用它们会什么都不做,方法不能被内部方法声明;只在类内部 - 你可以在该类内的方法(内部类)和方法中声明类。

相关问题