Why Is The Last Case Of My Switch Statement Getting Hit?
The last case of my switch statement in my Java app is always getting hit. How can I make this work properly? public void onClick(View v) { Random r = new Random();
Solution 1:
Case statements will 'fall through' in most languages without a break statement. You just need to add one to each case. Like this:
case 1:
setContentView(R.layout.image1);
break;
case 2:
setContentView(R.layout.image2);
break;
case 3:
setContentView(R.layout.image3);
break;
case 4:
setContentView(R.layout.image4);
break;
Solution 2:
You're falling through your case statements. You need to break
.
switch (x)
{
case1:
setContentView(R.layout.image1);
break;
case2:
setContentView(R.layout.image2);
break;
case3:
setContentView(R.layout.image3);
break;
case4:
setContentView(R.layout.image4);
break;
}
Take a look at this tutorial.
Solution 3:
You have to break;
every switch statements you have. If you don't break the statement then the next case will be hit (and so one until the last with a break).
case1:
setContentView(R.layout.image1);
break;
case2:
setContentView(R.layout.image2);
break;
case3:
setContentView(R.layout.image3);
break;
case4:
setContentView(R.layout.image4);
break;
default:
//Anything you want;break;
And... it's a good programming practice to use the default case (will be used if none of the cases is hit)
Post a Comment for "Why Is The Last Case Of My Switch Statement Getting Hit?"