Java 保留循环变量值的问题

Java 保留循环变量值的问题,java,android,Java,Android,这段代码中有一个错误,我将公共类变量mCountryCode声明为String for (mCountryCode : isoCountryCodes) { locale = new Locale("", mCountryCode); if(locale.getDisplayCountry().equals(mSpinner.getSelectedItem())) { mCountryCode = locale.getCountry();

这段代码中有一个错误,我将公共类变量mCountryCode声明为String

 for (mCountryCode : isoCountryCodes) {
     locale = new Locale("", mCountryCode);
     if(locale.getDisplayCountry().equals(mSpinner.getSelectedItem())) {
         mCountryCode = locale.getCountry();                        
         break;
     }
 }
如果我改为使用
for(String mCountryCode:isocountrycode)
,则错误将消失,但我无法在
中断后维持
mCountryCode
字符串值行。

是的,就是不能那样工作。它总是声明一个新变量

您可以使用:

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
语句中为字段赋值。

最好在
foreach中使用局部变量。

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

如果要在循环之外使用
mCountryCode
,必须在循环之前声明它

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
String mCountryCode=null;
对于(int i=0;i
您没有正确使用增强型for循环:您需要指定类型,如下所示:

for (String countryCode : isoCountryCodes) {
     ...
}
现在,您可以根据需要在循环中使用
countryCode
字符串