2014-01-14 80 views
0

我写了下面,这是在同一个包市级一类国家的一个toString和_cities是一个数组代表我的国家范围内的城市: ** 编辑: * *爪哇 - 对象存在DILEM

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不能解析到VARI能够“..任何建议?

谢谢!

+3

'referenceCityCenterr' VS'referenceCityCenter'。阅读变量范围。 –

+1

也想删除if语句中的“Point”,如果您试图将该值赋予该变量。 – JustinKSU

+0

我编辑的问题...现在有其他问题,而不是... PLZ读.. THX! – Batman

回答

1

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

您已声明referenceCityCenter在您的代码的该行不可见的范围内。尝试在方法开始时声明它(并且如果它是null,那么当它到达您的验证.isAbove()!时:P)

+0

吗?没有明白一切... thx – Batman

+0

亚斯马尼修好了! :)只要确保你控制空值,当他们问你一个你不知道在你的数组中的城市名称 –

+0

妥善保管:) thx! – Batman