Java – why are variables not local in case statements?

I recently added another menu item to the Android Java application and was surprised that eclipse represents the variable in the previous case: break is not local (so I just added a suffix to get it)

I'm a little confused in my mind. The first group: if you choose the second option, the rest will not be executed Can anyone explain my wrong idea?

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

Solution

Like C, in Java, a switch statement is not expected when viewed Abbreviations make it difficult to understand and do not create ranges It all boils down to C, and one of the switches is just syntax sugar The compiler converts the switch to multiple conditional jumps This allows the language to be used down, which is a function during C's design ("disconnect" is still optional) This Java feature is similar to C

switch(a):
    case 1:
        dosomething();
    case 2:
        dosomemore();

Translated into

if(a==1) jump ##1;
if(a==2) jump ##2;
jump ##3;
##1:
dosometing();
##2:
dosomemore();
##3:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>