我写了以下内容,这是一个Country类的toString,在同一包中具有City类,并且_cities是一个数组,表示我的Country中的城市:
**编辑:**

public String toString(){

    String allCitiesData = "";   //must be initialized

    for(int i=0;this._cities[i] != null;i++)//run all over the cities until reach the end(null cell)
    {   //concat new city to the string and adds a new line between
        allCitiesData = allCitiesData.concat(this._cities[i].toString()+"\n\n");
    }
    return allCitiesData;
}//toString method

public String citiesNorthOf(String cityName){
    String allCitiesNorthOf = "";// must be initialized

    for(int i=0; this._cities[i] != null ; i++)
    {
        if (this._cities[i].getCityName() == cityName)
        {
            Point referenceCityCenter = new Point(this._cities[i].getCityCenter());
        }
    }

    for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
    {
        if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
        {
            allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
        }
    }
}//citiesNorthOf method


但是,当我运行它时,它仅在此行显示一个错误:

if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))


Eclipse表示:“ referenceCityCenter无法解析为变量”。有什么建议吗?

谢谢 !!

最佳答案

referenceCityCenter超出范围。将其放在您的if语句之外,并确保随后检查null,如下所示:

public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized

Point referenceCityCenter = null;

for(int i=0; this._cities[i] != null ; i++)
{
    if (this._cities[i].getCityName() == cityName)
    {
        referenceCityCenter = new Point(this._cities[i].getCityCenter());
    }
}

for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
    if (referenceCityCenter !- null && this._cities[i].getCityCenter().isAbove(referenceCityCenter))
    {
        allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
    }
}
}

关于java - Java-对象存在困境,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21123246/

10-11 02:31