+ 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?

28th Mar 2023, 3:06 PM
MALAVIKA
MALAVIKA - avatar
2 Réponses
+ 7
MALAVIKA in which programming language are you talking about?
28th Mar 2023, 3:29 PM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar
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")
2nd Apr 2023, 6:44 AM
Zayn