Reputation:
I would like to have a switch that memorizes the menu that I am currently in and then check what button is pressed so it can direct me to another activity.
Currently I have come up with this but for some reason when I am debugging the second case so: case R.id.bt1
isn't even reached.
I have put in the variable class: public static int currentMenu = 0;
but when I set this to 1 my debugger goes all weird.
Can anyone figure out what I might have done wrong?
@Override
public void onClick(View view) {
int currentMenu = Variables.currentMenu;
switch (currentMenu) {
case 0:
switch (view.getId()) {
case R.id.bt1:
currentMenu = 1;
Variables.currentMenu = currentMenu;
checkMenu();
break;
case R.id.bt2:
currentMenu = 2;
Variables.currentMenu = currentMenu;
checkMenu();
break;
case R.id.bt3:
break;
}
case 1:
switch (view.getId()) {
case R.id.bt1:
currentMenu = 0;
Variables.currentMenu = currentMenu;
checkMenu();
break;
case R.id.bt2:
Intent adam = new Intent(Home.this, BattleScene.class);
startActivity(adam);
Variables.currentMenu = 0;
break;
case R.id.bt3:
break;
}
}
Upvotes: 1
Views: 98
Reputation: 140467
The immediate answer: you missed a break for your outer switch.
But why did that happen - leads to the real answer here: do not even try to write such code.
This is a gross violation of the Single Layer of Abstraction principle.
And the effects of that are obvious: such code turns spaghetti code the moment you close your editor. You even seem to try to change the content of the variable your are switching on the "outer" side while being "inside". Mind boggling. In a negative way.
In other words: you just started writing this code, but you can't get it correct. And the reason is because you are decided to use a complicated way of expressing your thoughts.
Long story short: using switches to make decisions and drive behavior is "procedural" programming. The OOP way of handling such things: use a state machine. And instead of asking for state and switching about it, invoke methods on objects. And those objects maybe return other objects you can invoke methods on.
Upvotes: 3
Reputation: 2276
There is a fall-through in your outer switch
. Just as you do in the inner switch
you most probably want to break
at the end of each case
.
@Override
public void onClick(View view) {
int currentMenu = Variables.currentMenu;
switch (currentMenu) {
case 0:
switch (view.getId()) {
// omitted for readability
}
break; // <-- outer break
case 1:
switch (view.getId()) {
// omitted for readability
}
break; // <-- outer break
}
Upvotes: 1