In: Computer Science
Re-write following if-else-if statements as Switch statement. Your final code should result in the same output as the original code below.
if (selection == 10)
System.out.println("You selected 10.");
else if (selection == 20)
System.out.println("You selected 20.");
else if (selection == 30)
System.out.println("You selected 30.");
else if (selection == 40)
System.out.println("You selected 40.");
else System.out.println("Not good with numbers, eh?");
2.
Write a Constructor for the TrafficLight class that sets stopLight value to “red”, waitLight to “yellow” and goLight to “green”?
Hey There,
- I understood your question and I have given the answer to the best of my knowledge.
- I have also put comments in the code so that you can also understand what I did in the code.
- If you need further explanations then do let me know in the comments box I will be more than happy to help you.
Answer:
Question 1:
- Below I have provided the switch case implementation of the given if else-if code.
- While using the switch case we use break after all the cases so that once the switch case matches it does not go to the next case.
- Switch Implementation code:
switch(selection){
case 10: System.out.println("You selected 10.");
break;
case 20: System.out.println("You selected 20.");
break;
case 30: System.out.println("You selected 30.");
break;
case 40: System.out.println("You selected 40.");
break;
default: System.out.println("Not good with numbers, eh?");
}
Question 2:
- Constructor is a block of codes similar to the method. It is called when an instance of the class is created. It is mainly used to initialize the object.
- The name of constructor is same as the class name.
- Below I have provided the given constructor code as asked in the question:
// Declaring variables
String stopLight;
String waitLight;
String goLight;
// Defining constructor
TrafficLight(){
stopLight = "red";
waitLight = "yellow";
goLight = "green";
}
- Below here I have also provided the whole code so that you can understand well.
- Here I have also used the display method that will print the values of stopLight, waitLight and goLight. By this we can confirm that our code is working correctly.
public class TrafficLight
{
// Declaring variables
String stopLight;
String waitLight;
String goLight;
// Defining constructor
TrafficLight(){
stopLight = "red";
waitLight = "yellow";
goLight = "green";
}
// This function will print values of stopLight, waitLight and goLight
void display(){
System.out.println(stopLight);
System.out.println(waitLight);
System.out.println(goLight);
}
// main method
public static void main(String[] args) {
// Creating object of TrafficLight class
TrafficLight t1 = new TrafficLight();
// Calling display method
t1.display();
}
}
Screenshot of it working correctly:
Hope it helps:)