Android 将switch语句更改为if语句
我想将这个switch语句更改为if语句或while循环。 我该怎么做? 请注意使用Android Studio的这段代码Android 将switch语句更改为if语句,android,if-statement,switch-statement,Android,If Statement,Switch Statement,我想将这个switch语句更改为if语句或while循环。 我该怎么做? 请注意使用Android Studio的这段代码 public void onClick(View v) { switch(v.getId()){ case R.id.button: Log.v(TAG, "verbose"); break; case R.id.button2: Log.d(TAG, "Debug"); break;
public void onClick(View v) {
switch(v.getId()){
case R.id.button:
Log.v(TAG, "verbose");
break;
case R.id.button2:
Log.d(TAG, "Debug");
break;
case R.id.button3:
Log.i(TAG, "Information");
break;
case R.id.button4:
Log.w(TAG, "Warning");
break;
case R.id.button5:
Log.e(TAG,"Error");
break;
}
}
我建议您使用现有的
switch
语句,但如果您确实想要if
,可以这样做:
public void onClick(View v) {
int id = v.getId();
if (id == R.id.button) {
Log.v(TAG, "Verbose");
} else if (id == R.id.button2) {
Log.d(TAG, "Debug");
} else if (id == R.id.button3) {
Log.i(TAG, "Information");
} else if (id == R.id.button4) {
Log.w(TAG, "Warning");
} else if (id == R.id.button5) {
Log.e(TAG, "Error");
}
}
如果您使用的是AndroidStudio,那么可以使用intent
开关
关键字上alt+enter
(在Mac上,不确定Windows)将“开关”替换为“如果”
注意:您可以使用相同的方法替换if来切换。我不理解这个问题,只需使用if的开关盒就可以了。这是一个很好的选择,为什么您要使用if…elseif来选择bn 2选项,并且在多个选项之间使用开关。此外,在多个选项的情况下,开关的性能更好。