I am using a Java switch statement to assign different values to a variable based on the id of the button that called it.
The problem is that it always evaluates to the detail.
I think the error might be in how I am getting the Id (the R.java bit), but I have done some internet research, and can’t find the ‘proper’ way of doing it.
This is my code (the -99 and 23 are there so it was obvious if it wasn’t working)
public void rootMe(View v){
/* I got rid of some code here so it was shorter */
int mult = -99;
int buttonId = v.getId();
switch(buttonId)
{
case R.id.root2:
mult = 1/2;
case R.id.root3:
mult = 1/3;
case R.id.root4:
mult = 1/4;
case R.id.root5:
mult = 1/5;
case R.id.root6:
mult = 1/6;
default:
mult = 23;
}
With a
swicthconstruct, once acasehas been reached, the code below thatcasewill be executed — even if there is anothercasestatement.If you want the execution to stop (to exit the
switchconstruct), you must use abreakstatement ; most probably at the end of each one of yourcaseblocks :This way, when the code that corresponds to a
casestatement is executed, it will no longer execute the code that corresponds to the followingcases statements, and exit theswitchconstruct.Note that this is not android-specific : it’s just the way the
switchstatement works in JAVA ; see for exemple : TheswitchStatement