❔ Classes and objects
Hi guys, I need help solving this problem: Write a class to model a Lamp.
Provide the following methods in your class:
a) turnOn – turn ON the lamp
b) turnOff – turn OFF the lamp
c) showCurrentColor – outputs current color of lamp
Each time the lamp is turned ON, it shows a different color. The changing
color-sequence is Red, Green, Blue, then loops back to Red and so on.
The state of the lamp is initially OFF. When the lamp is turned ON for the
first time, its color should be Red.
Note that the lamp cannot be turned ON if it is already ON. Its state
needs to be OFF before a call to turnOn() has any effect.
Test that your lamp exhibits the correct color-changing order by turning
it ON and OFF 10 consecutive times.
I am stuck here, not sure how to proceed...
9 Replies
The class members you have described as Attributes are referred to as fields. They are usually private and have the following naming scheme:
private bool _isOn;
If you wish to have a publicly available field, use properties:
public bool IsOn { get; set; }
I'm not quite sure what the switch array is supposed to be
I recommend storing the current color as a number
After each on/off you increase the color number.
0 Red
1 Green
2 Blue
Once you increase the number and it is equal to 3, change the value back to 0 to restart.
Write a method that uses a switch to convert said number to a string representation of the color:
is the more modern way of writing that method 🙂
If you can be more specific about where you are stuck and why, that would help.
Thank you guys!! Would using a double for loop be overcomplicating things? haha
yes
Try this for now. There are additional improvements applicable to the code I've provided above; however, I don't want to overwhelm you too much
Thank you so much guys, it's really helpful 🥺 🫡 🙏 appreciate it loads
Good stuff, but try to spoonfeed less in the future.
Thanks for the feedback
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.