我正在使用HashMap。我的代碼會編譯,但是當我運行它時,我沒有得到我應該期待的。我的代碼爲printAllNeighbors
和getNeighbor
不起作用。誰能幫我。我想我明白我在做什麼,這就是爲什麼我很困惑。HashMap問題,打印鄰居
import java.util.HashMap;
public class House
{
private int streetNumber;
private String streetName;
private String owners;
HashMap <String, House> myNeighbors;
public House (int streetNumber, String streetName, String lastName)
{
streetNumber = streetNumber;
streetName = streetName;
lastName = owners;
myNeighbors = new HashMap <String, House>();
}
public int getStreetNumber()
{
return streetNumber;
}
public String getStreetName()
{
return streetName;
}
public String getLastName()
{
return owners;
}
public void setStreetNumber(int streetNumber)
{
streetNumber =this.streetNumber;
}
public void setStreetName(String streetName)
{
streetName = this.streetName;
}
public void setLastName(String lastName)
{
owners = lastName;
}
public void addNeighbor (String direction, House h)
{
myNeighbors = new HashMap <String, House>();
}
public House getNeighbor (String direction)
{
if(direction.equals(direction)){
return getNeighbor(direction);
}
else{
return null;
}
}
public void printAllNeighbors()
{
for (String key : myNeighbors.keySet())
{
System.out.println("\nkey: " + key + " value: " + myNeighbors.get(key));
}
}
public String toString()
{
return "Address: " + streetNumber + " " + streetName + "\nOwner: " + owners;
}
public static void main (String [] args)
{
House whiteHouse = new House (1600, "Pennsylvania Ave", "Obama");
House jerrysHouse = new House (1602, "Pennsylvania Ave", "Mabrito");
House guentersHouse = new House (1604, "Pennsylvania Ave", "Tusch");
House anasHouse = new House (1609, "Pennsylvania Ave", "Posada");
whiteHouse.addNeighbor("east", jerrysHouse);
whiteHouse.addNeighbor("south", guentersHouse);
whiteHouse.addNeighbor("north west", anasHouse);
System.out.println(whiteHouse);
whiteHouse.printAllNeighbors();
System.out.println("****************************** \n" + jerrysHouse);
jerrysHouse.printAllNeighbors();
System.out.println("****************************** \n" + guentersHouse);
guentersHouse.printAllNeighbors();
System.out.println("****************************** \n" + anasHouse);
anasHouse.printAllNeighbors();
}
}
我想你需要告訴我們你得到了什麼,以及你的期望。 – ThisClark
我得到空0,業主0,我期待得到白宮,jerrysHouse,guentersHouse等的鄰居。 –
嗨@Deborah_Watson如果任何答案已解決您的問題,請點擊複選標記考慮[接受它](http://meta.stackexchange.com/q/5234/179419)。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 – gastonmancini