user1502550
user1502550

Reputation: 31

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();
    int x=r.nextInt(4-1) + 1;
    switch (x)
    {
    case 1:
        setContentView(R.layout.image1);
    case 2:
        setContentView(R.layout.image2);
    case 3:
        setContentView(R.layout.image3);
    case 4:
        setContentView(R.layout.image4);

Upvotes: 2

Views: 1762

Answers (3)

Nick Mooney
Nick Mooney

Reputation: 111

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;

Upvotes: 11

Greg Kopff
Greg Kopff

Reputation: 16545

You're falling through your case statements. You need to break.

switch (x)
{
  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;
}

Take a look at this tutorial.

Upvotes: 5

yugidroid
yugidroid

Reputation: 6690

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).

    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;
    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)

Upvotes: 1

Related Questions