Home > Software engineering >  How do I print the boolean value?
How do I print the boolean value?

Time:12-13

Okay, so I'm currently trying to write the code for a very inaccurate stoplight--one that is only meant to help me understand what I've learned, but I can't seem to figure it out! In my code, at the very end, I say print("Green Light!") after setting up a few variables, but I would like to indicate what the computer should do instead of flat out saying "print this phrase," if that makes sense... not sure it does.

How would I write this if I wanted to simply print the Boolean value of greenLight without saying print("Green Light!")?

I'm very much a beginner and I might be asking the wrong question--I know that, but I'm hoping someone can help!

Something tells me I haven't learned enough to do this, yet, but I really wanna know how this works.

This is what I've written so far. It runs, but I would like to change it so all I have to say is print(greenLight) or print(Bool).

When I try putting in print(greenLight), it returns an error:

Output: Review.swift:14:7: error: variable 'greenLight' used before being initialized print(greenLight) ^ Review.swift:4:5: note: variable defined here var greenLight: Bool ^

var carAtRightIntersection = false
var carAtLeftIntersection = false
var carStraightAhead = true
var greenLight: Bool

if !(carAtRightIntersection && carAtLeftIntersection) && carStraightAhead {
  greenLight = true
}

if carAtRightIntersection && carAtLeftIntersection && !(carStraightAhead) {
  greenLight = false
}

print("Green light!")

CodePudding user response:

If you don't want to print the actual phrases, You could use a switch case statement

switch greenLight{

case true:
    print("Green Light!")

case false:
    print("Red Light!")

default:
    print("Yellow Light!")
}

After the first block executes

  • Related