2016-01-21 116 views
0

我在這段代碼中有一個錯誤,我已經聲明公共類變量mCountryCode爲字符串。問題與保留循環變量值

for (mCountryCode : isoCountryCodes) { 
    locale = new Locale("", mCountryCode); 
    if(locale.getDisplayCountry().equals(mSpinner.getSelectedItem())) { 
     mCountryCode = locale.getCountry();       
     break; 
    } 
} 

如果我使用for (String mCountryCode : isoCountryCodes)而不是那麼錯誤就會消失,但我不能後break;線維持mCountryCode字符串值。

回答

6

是的,enhanced for statement只是不這樣工作。它總是聲明一個新的變量。

您可以使用:

for (String tmp : isoCountryCodes) { 
    mCountryCode = tmp; 
    ... 
} 

...雖然坦言這是做一個非常奇怪的事情。在我看來,你真的不希望分配mCountryCode,但只有一個匹配:

for (String candidate : isoCountryCodes) { 
    Locale locale = new Locale("", candidate); 
    if (locale.getDisplayCountry().equals(mSpinner.getSelectedItem())) { 
     mCountryCode = candidate; 
     break; 
    } 
} 

請注意,這不分配給現有locale變量,但聲明每次迭代都會有一個新的。這幾乎肯定是一個更好的主意......如果需要,您總是可以在if聲明中指定一個字段。

+0

非常感謝你的工作...... –

0

這將是更好,如果你想使用循環mCountryCode外使用局部變量在foreach

for (String code : isoCountryCodes) { 
    locale = new Locale("", code); 
    if(locale.getDisplayCountry().equals(mSpinner.getSelectedItem())){ 
     mCountryCode = locale.getCountry();       
     break; 
    } 
} 
0

,你必須將循環

String mCountryCode = null; 
for(int i = 0; i < isoCountryCodes.length(); i++){ 
    locale = new Locale("", isoCountryCodes[i]); 

    if(locale.getDisplayCountry().equals(mSpinner.getSelectedItem())){ 
     mCountryCode = locale.getCountry();       
     break; 
    } 
} 

//mCountryCode is still assigned 
2

你」之前聲明它請勿正確使用增強的for循環:您需要指定類型,如下所示:

for (String countryCode : isoCountryCodes) { 
    ... 
} 

現在,您可以根據需要在循環中使用countryCode字符串。