+ 1
Can we accept a string value in switch case?
I'm on level 3 switch case programs and my task involves accepting a string value in switch case. What should I do?
2 Answers
+ 7
MALAVIKA in which programming language are you talking about?
0
Yes you can
In java and most other languages it'll be like this:
string someString = "hey";
switch (someString)
{
case "hello":
// Do something
break;
case "world":
// Do something else
break;
default:
// If the string doesn't match any of the cases, execute the code here
}
You can use a switch statement for all types like int, string, float, double, etc.
But you need to be careful with the value you provide for each case since it can not be a variable (it has to be a constant value, like "some text" or 56) and it has to have a matching type with the value/variable in the switch parentheses. (for example the type of someString variable is string, so all the cases that you're comparing it to should be strings, like "hello")