写一个简单函数,使Add a method called “switchLight” which turns the light on if it is off, and vice versa
时间: 2024-09-25 07:11:57 浏览: 35
当然,我们可以创建一个简单的 `Light` 类,包含一个私有布尔变量 `isOn` 来表示灯的状态,然后定义一个名为 `switchLight` 的公共方法来切换灯。这里是一个Java示例:
```java
public class Light {
private boolean isOn;
public Light() {
this.isOn = false; // 默认灯关闭
}
// Getter and Setter for isOn property
public boolean getIsOn() {
return isOn;
}
public void setIsOn(boolean isOn) {
this.isOn = isOn;
}
/**
* Method to switch the light on or off based on its current state.
*/
public void switchLight() {
if (isOn) {
System.out.println("Turning off the light.");
isOn = false;
} else {
System.out.println("Turning on the light.");
isOn = true;
}
}
}
// Usage example
public class Main {
public static void main(String[] args) {
Light light = new Light();
light.switchLight(); // Initially, prints "Turning on the light."
light.switchLight(); // After first call, prints "Turning off the light."
}
}
```
这个 `switchLight` 方法检查当前灯是否打开,如果打开则关闭,反之则打开。你可以根据需要扩展这个类或添加更多的功能。
阅读全文