Aalap Patel
Aalap Patel

Reputation: 2076

Issue with retaining loop variable value

I have an error in this piece of code where I have declared public class variable mCountryCode as String.

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

If I use for (String mCountryCode : isoCountryCodes) instead then the error will go away but I am not able to sustain the mCountryCode string value after break; line.

Upvotes: 0

Views: 139

Answers (4)

Jonas Czech
Jonas Czech

Reputation: 12328

You're not using the enhanced for loop correctly: you need to specify the type, like this:

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

Now you can use yourcountryCode string in your loop as needed.

Upvotes: 2

TheoKanning
TheoKanning

Reputation: 1639

If you want to use mCountryCode outside of the loop, you must declare it before the loop

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

Upvotes: 0

meda
meda

Reputation: 45490

It would be better to use a local variable in your foreach

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500785

Yup, the enhanced for statement just doesn't work like that. It always declares a new variable.

You can use:

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

... although frankly that's a pretty odd thing to do. It seems to me that you don't really want to assign every value to mCountryCode, but only the matching one:

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

Note that this doesn't assign to an existing locale variable, but declares a new one in each iteration. That's almost certainly a better idea... you can always assign to a field in the if statement if you need to.

Upvotes: 6

Related Questions