为了解决当前问题,我进行了很多研究,但是,我不确定出了什么问题:
import java.util.Map;
import java.util.HashMap;
public class Items
{
public static void main (String args[])
{
HashMap<String, Double> Hallway = new HashMap<String, Double>();
HashMap<String, Double> Toilet = new HashMap<String, Double>();
HashMap<String, Double> ChemistryLab = new HashMap<String, Double>();
HashMap<String, Double> Outdoors = new HashMap<String, Double>();
HashMap<String, Double> Library = new HashMap<String, Double>();
HashMap<String, Double> Engineering = new HashMap<String, Double>();
HashMap<String, Double> Cafeteria = new HashMap<String, Double>();
HashMap<String, Double> ComputerLab = new HashMap<String, Double>();
HashMap<String, Double> LectureTheater = new HashMap<String, Double>();
HashMap<String, Double> MedicalCentre = new HashMap<String, Double>();
}
public HashMap<String, Double> getHallwayItems()
{
return Hallway;
}
public HashMap<String, Double> getToiletItems()
{
return Toilet;
}
public HashMap<String, Double> getChemistryLabItems()
{
return ChemistryLab;
}
public HashMap<String, Double> getOutdoorItems()
{
return Outdoors;
}
public HashMap<String, Double> getLibraryItems()
{
return Library;
}
public HashMap<String, Double> getEngineeringItems()
{
return Engineering;
}
public HashMap<String, Double> getCafeteriaItems()
{
return Cafeteria;
}
public HashMap<String, Double> getComputerLabItems()
{
return ComputerLab;
}
public HashMap<String, Double> getLectureTheaterItems()
{
return LectureTheater;
}
public HashMap<String, Double> getMedicalCentreItems()
{
return MedicalCentre;
}
}
它说当我尝试编译时找不到变量 Hallway,但是我不知道如何解决这个问题。 感谢您提供的任何帮助。
最佳答案
Hallway
是 main 函数内的局部变量。 main 也是一个静态函数。这些在 main
中声明的变量不能被其他函数访问。
有两种选择,
1) 将所有 map 声明为对象的静态成员,并具有 static getHallway()
static getToilet
等。
2)我个人建议这样做,
导入java.util.Map; 导入java.util.HashMap;
public class Items
{
private HashMap<String, Double> Hallway = new HashMap<String, Double>();
private HashMap<String, Double> Toilet = new HashMap<String, Double>();
...
public HashMap<String, Double> getHallwayItems()
{
return Hallway;
}
...
...
public static void main (String args[])
{
Items myItem = new Items();
myItem.getHallwayItems(); // and do whatever you want.
}
}
这样,我们也可以利用 OOPS...
关于Java - 使 HashMap 可从其他类使用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22843880/