问题描述
我最近在android java应用程序中添加了另一个菜单项,并且很惊讶Eclipse说来自前一个案例的变量:break不是本地的(所以我刚刚添加了一个后缀来获取)。
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;`
推荐答案
与C一样,在Java中,switch语句不是人们在查看它时所期望的。压力使得很难理解未创建范围。这一切都归结为C,其中一个开关只是语法糖。编译器将切换转换为许多条件跳转。这使得语言能够使用直通,这是在设计C期间的特征(中断仍然是可选的)。此Java功能仍与C兼容。
As in C, in Java a switch statement is not what one would expect when looking at it. The indendation makes it difficult to understand that a scope is not created. This all boils down to C, where a switch is just syntactic sugar. The compiler transforms a switch into a number of conditional jumps. This enables the language to use fall-through, a feature that during the design of C was intended ("break" remained optional). This Java feature remained compatible to C.
switch(a):
case 1:
dosomething();
case 2:
dosomemore();
被翻译成
if(a==1) jump ##1;
if(a==2) jump ##2;
jump ##3;
##1:
dosometing();
##2:
dosomemore();
##3:
这篇关于为什么变量在case语句中不是本地的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!