2014-01-14 124 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