Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

java - Why are variables not local in case statements?

I recently add another menu item to an android java app and was suprised that Eclipse said that variable from the previous case:break were not local (So I've just added a suffix to get by).

I'm a bit confused as in my mind, the 1st set of case:break would not be executed at all if the 2nd option was chosen. Could someone explain my faulty thinking please?

        case R.id.menuDebugMode:
            debugMode = !debugMode;
            if (debugMode){
                Toast.makeText(mainActivity.this, "Debug Mode on - NOT TO BE USED WHILST DRIVING", Toast.LENGTH_LONG).show();           
            } else {
                tvDebug.setText("");
                tvInfo.setText("");
            }
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("debugMode", debugMode);
            editor.commit();
        break;

        case R.id.menuSpeedMode:
            speedSignMode = !speedSignMode;
            if (speedSignMode){
                Toast.makeText(mainActivity.this, "SpeedSign Mode in use", Toast.LENGTH_LONG).show();           

            } else {
                    Toast.makeText(mainActivity.this, "MapSpeed Mode in use", Toast.LENGTH_LONG).show();            
            }
            SharedPreferences settings2 = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor2 = settings2.edit();
            editor2.putBoolean("speedSignMode", speedSignMode);
            editor2.commit();
        break;`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're right that at most one will execute, but a case does not create a new scope. You can manually create a block with its own scope.

case foo:
    {
       int var = ...
    }
    break;

case bar:
    {
       int var = ...
    }
    break;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...