0

I have read some code about Switch statement in Java Language. I noted that written the next code, I have this output:

FEBO SERR JANUO January 2

Code:

    int month = 2;
    String monthString = "";
    switch (month) {
        case 2:
            monthString = "FEB";
            System.out.print("FEBO ");
        default:
            monthString = "ERROR";
            System.out.println("SERR ");
        case 1:
            monthString = "January";
            System.out.println("JANUO ");
            break;
    }

    System.out.print(monthString+ " ");
    System.out.print(month);

I hoped the next output really:

FEBO SERR FEB 2

Why I got that first output?

Thanks in advance.

Fernando Pie
  • 895
  • 1
  • 12
  • 28
  • 1
    Because month is `2`. You get the second output because you have no `break` for `case 2` (or `default`) so the statements fallthrough. – Elliott Frisch Aug 12 '20 at 02:37
  • 1
    In switch, each of the cases should end with `break` statement. If you didn't put a `break` , all the cases will be applied. That is why you are having this kind of output. – BlackList96 Aug 12 '20 at 02:39
  • Ok. I can get a simple answer: if a case not ends in a **break** statement all cases are applied! Also each cases should ends with break! Haha – Fernando Pie Aug 12 '20 at 02:41

2 Answers2

0

Im not sure if I understand what you want but I think this is what you want:

    int month = 1;
    String monthString = "";
    switch (month) {
        case 1:
            monthString = "JAN";
            System.out.println("JANUO ");
            break;
        case 2:
            monthString = "FEB";
            System.out.println("FEBO ");
            break;
        default:
            monthString = "ERROR";
            System.out.println("SERR ");
            break;
    }

    System.out.print("SERR " + monthString+ " ");
    System.out.print(month);

Your problem was that you forgot to put the break; after each cases. Also, I didnt see any purpose of why you didnt put it into the correct order and (I think?) you did a typo at System.out.print("FEBO "); based on the other ones, it should be System.out.println("FEBO "); and finally, since you mentioned of wanting SERR in each output I adjusted that for you.

Reminder: println will print your text AND a new line (\n) while print wont print any.

Jessy Guirado
  • 220
  • 1
  • 7
0

Add break at the end of each case.

switch(condition) {
   case VALUE1:
          // do something
          break;
   default:
          // do default something
}
Suman
  • 818
  • 6
  • 17