JAVA电视遥控器类与测试
时间: 2023-06-10 21:09:04 浏览: 236
java-遥控器
下面是一个简单的JAVA电视遥控器类和测试代码:
```java
public class TVRemote {
private int channel;
private int volume;
private boolean isOn;
public TVRemote() {
channel = 1;
volume = 50;
isOn = false;
}
public void turnOn() {
isOn = true;
System.out.println("TV is turned on.");
}
public void turnOff() {
isOn = false;
System.out.println("TV is turned off.");
}
public void setChannel(int channel) {
if (isOn) {
this.channel = channel;
System.out.println("Channel is set to " + channel);
} else {
System.out.println("TV is turned off. Cannot set channel.");
}
}
public void setVolume(int volume) {
if (isOn) {
this.volume = volume;
System.out.println("Volume is set to " + volume);
} else {
System.out.println("TV is turned off. Cannot set volume.");
}
}
public void printStatus() {
System.out.println("TV is " + (isOn ? "on" : "off"));
if (isOn) {
System.out.println("Channel is " + channel);
System.out.println("Volume is " + volume);
}
}
}
```
测试代码:
```java
public class TVRemoteTest {
public static void main(String[] args) {
TVRemote tv = new TVRemote();
tv.printStatus(); // TV is off
tv.turnOn(); // TV is turned on
tv.setChannel(3); // Channel is set to 3
tv.setVolume(70); // Volume is set to 70
tv.printStatus(); // TV is on, Channel is 3, Volume is 70
tv.turnOff(); // TV is turned off
tv.setChannel(5); // TV is turned off. Cannot set channel.
tv.setVolume(80); // TV is turned off. Cannot set volume.
tv.printStatus(); // TV is off
}
}
```
输出结果:
```
TV is off
TV is turned on
Channel is set to 3
Volume is set to 70
TV is on
Channel is 3
Volume is 70
TV is turned off
TV is turned off. Cannot set channel.
TV is turned off. Cannot set volume.
TV is off
```
这个简单的电视遥控器类实现了开关、设置频道和音量以及打印电视状态的功能。测试代码展示了如何使用这个类。
阅读全文