Ashley P.

asked • 10/03/19

Java Switch Case

How do we write the following code using switch statement ?


if(option == 1)

vehicle = "Motor Cycle" ;

else if(option == 2)

vehicle = "Car";

else if(option == 3) || (option == 4)

vehicle = "Heavy Vehicle";

else if(option == 5)

vehicle = "Three Wheeler";

else

vehicle = "Invalid Option";


1 Expert Answer

By:

David K. answered • 10/03/19

Adjunct Professor and Professional Tutor

Ashley P.

Thanks for the response : I tried the same code without the opening and closing square brackets you've used for seperating different cases. Is that also correct? NetBeans didn't show any errors and results were there too
Report

10/03/19

David K.

tutor
Yes, the curly braces are not needed in the case sections, but, I always include them for readability; it is just my adopted coding standard and a habit I cannot break.
Report

10/03/19

Ashley P.

I understand! And what about the input() part? Is that also a compulsory line?
Report

10/04/19

David K.

tutor
When we create a Scanner, if we do not do a .close() on it, eclipse or other tools will nag us that we did not close it, whenever you open a reader or writer, you should always close it. I am assuming that is what you were talking about.
Report

10/04/19

Ashley P.

I coded using the NetBeans IDE and did not write that line and there were no errors and the code executed smoothly. Thats why I
Report

10/04/19

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.