Magnus
Magnus

Reputation: 728

Java beginner: Switch statement does not give expected output

    char suit = 'S';
    int n = 2;


    for (int k= 0; k<4; k++){
    for (int i = 0; i < n; i++){

        switch (k) {
        case 0: suit = 'S';
        case 1: suit = 'H';
        case 2: suit = 'D';
        case 3: suit = 'C';
        }

This is a code excerpt from an assignment.

Suit is set to 'C' after the switch statement, and it never changes throughout the double loop, according to the debugger. What have I misunderstood about the switch-statement?

Upvotes: 1

Views: 154

Answers (2)

MSB
MSB

Reputation: 884

You need to add a break statement at the end of each block like so:

switch (k) {
        case 0: 
          suit = 'S'; 
          break;
        case 1: 
          suit = 'H';
          break;
        case 2: 
          suit = 'D';
          break;
        case 3: 
          suit = 'C';
          break;
        default:
          break;
        }

If you do not end a block with a break statement your switch will continue onto the next block and execute that code too (if the case is valid).

usages where this behaviour might be desired can be found here

Upvotes: 0

nano_nano
nano_nano

Reputation: 12523

switch (k) {
        case 0: 
          suit = 'S'; 
          break;
        case 1: 
          suit = 'H';
          break;
        case 2: 
          suit = 'D';
          break;
        case 3: 
          suit = 'C';
          break;
        default:
          break;
        }

without the break; you enter each case block till the first break is reached.

Upvotes: 7

Related Questions