I’m solving this question:
Create a String
variable called currentLightColor
and set its value to "Green"
, "Yellow"
, or "Red"
.
Create conditional if
/ else if
/ else
logic to print: "The light is X"
where X is the value of the light variable. The if
/ else if
/ else
clause should print the appropriate color.
I have tried the code below but it is not working out well for me
fun main() {
var currentLightColor = "green"; "yellow"; "Red"
if (currentLightColor == "green") {
println("the light is green")
} else if (currentLightColor == "yellow") {
println("the light is yellow")
} else {
println("The light is Red")
}
}
Can anyone solve this please?
CodePudding user response:
You can use a when-structure if that is allowed:
var currentLightColor = "green"
when (currentLightColor) {
"green" -> println("the light is green")
"yellow" -> println("the light is yellow")
"red" -> println("the light is red")
else -> println("unknown light")
}
CodePudding user response:
You could do that without any conditional logic, just using a reference to the variable in the String
to be printed:
fun main() {
// example list of all valid lights
var lightColors = listOf("green", "yellow", "red")
// print the same sentence for each value
lightColors.forEach { println("the light is $it") }
}
Output:
the light is green
the light is yellow
the light is red
The problem here is you cannot react to an invalid value (e.g. "Blue"
).
Either use the answer by @Twistleton (maybe reference the variable instead of hard-coding the String
to be printed), or use your current one with the reference to the variable, maybe like this:
fun main() {
var currentLightColor = "blue";
if (currentLightColor == "green") {
println("the light is $currentLightColor")
} else if(currentLightColor == "yellow") {
println("the light is $currentLightColor")
} else if (currentLightColor == "red") {
println("the light is $currentLightColor")
} else {
println("unknown color $currentLightColor")
}
}
Output here:
unknown color blue
As you can see in the second example, you would only need conditional logic if you are expecting invalid colors. Otherwise, the simple first example should be sufficient.