-3

So I would have a code like this

switch (in) {
case "Hi":
  out = "Hello"
case "Who are you":
  out = "I am your personal Assistant 'Buddy'"
}
return out;

and in another class I would have

System.out.println(getAnwser(in));

So I would Hi and switch would give me: "I am your personal Assistant 'Buddy' "

But It should give me "Hello"

Any Idea why that happens??

azro
  • 53,056
  • 7
  • 34
  • 70
CodingWithAdin
  • 307
  • 1
  • 7
  • 18
  • 13
    you forgot to add break statements – Lino Jul 03 '18 at 13:37
  • The duplicate link is not _exact_, but the accepted answer correctly explains what you are seeing. If someone has a better link, then feel free to edit. – Tim Biegeleisen Jul 03 '18 at 13:40
  • 1
    You enter in the first `case` statement but as you forgot the `break` statement, you then enter in the second `case` statement. In the end, `out` contains the second string. – Arnaud Denoyelle Jul 03 '18 at 13:42
  • [The answer](https://stackoverflow.com/questions/50013682/abstract-class-return/50013853#50013853) – zlakad Jul 03 '18 at 13:43

1 Answers1

-2

The reason your code is not working because you forgot to close the case statement with breaks. Hence in your case, the "out" variable is first assigned Hello and then it is assigned **I am your personal Assistant 'Buddy' ** since nothing is stopping the compiler from doing so. Hence, you should use break. Edited code:

switch(in){
        case "Hi":
            out = "Hello";
            // add a break here to escape the switch statement
            break;
        case "Who are you":
            out = "I am your personal Assistant 'Buddy'";
            // always add a break, always...
            break;

            return out;
          }
MGT
  • 173
  • 12
  • 4
    Code only answers are discouraged on Stack Overflow. So please *edit* your answer and explain what this does and why it should be used – Lino Jul 03 '18 at 13:42
  • 3
    your code is missing a closing } (, a default statement) and an explanation – Stultuske Jul 03 '18 at 13:43