Reputation: 7070
Why is this code not returning right Color
? Everytime, it is executed with name="YELLOW"
or name="RED"
, it returns Color.WHITE
.
Color recieveColor(String name)
{
Color color=new Color(255,0,0);
switch(name)
{
case "YELLOW":
{
color=Color.YELLOW;
}
case "RED":
{
color=Color.RED;
}
case "WHITE":
{
color=Color.WHITE;
}
}
return color;
}
Upvotes: 1
Views: 109
Reputation: 11093
Although the question is answered a few times (using the break
keyword, to omit fallthrough), I'd like to give you some advice on the matter by using return
. This omits the entire problem: it can't go wrong with `returns.
switch (name) {
case "YELLOW":
return Color.YELLOW;
case "RED":
return Color.RED;
case "WHITE":
return Color.WHITE;
default:
return Color.BLACK;
}
Upvotes: 0
Reputation: 359
That is because you do not have a break
; after the color
has been assigned.
Upvotes: 0
Reputation: 708
This is because you don't have break
.
Also you can put default in case your color name does not match
switch (name) {
case "YELLOW":
color = Color.YELLOW;
break;
case "RED":
color = Color.RED;
break
case "WHITE":
color = Color.WHITE;
break;
default:
color = Color.YELLOW;
break;
}
Upvotes: 3
Reputation: 35587
You must use break
in switch case
. break
needs to exit from case
.
switch (name) {
case "YELLOW":
color = Color.YELLOW;
break;
case "RED":
color = Color.RED;
break
case "WHITE":
color = Color.WHITE;
break;
}
Else you will always have color white
Java
switch cases
.
Upvotes: 2