0

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.

0

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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;
     }
 }

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.