下面是一个简单的 Java 类来模拟组装计算机、进行开机、关机、待机等操作,并用状态变量表示计算机的状态:
public class Computer {
private String name;
private boolean isOn;
private boolean isSleeping;
public Computer(String name) {
this.name = name;
this.isOn = false;
this.isSleeping = false;
}
public void powerOn() {
if (!this.isOn) {
System.out.println("Turning on " + this.name + "...");
this.isOn = true;
this.isSleeping = false;
System.out.println(this.name + " is now on.");
} else {
System.out.println(this.name + " is already on.");
}
}
public void powerOff() {
if (this.isOn) {
System.out.println("Turning off " + this.name + "...");
this.isOn = false;
this.isSleeping = false;
System.out.println(this.name + " is now off.");
} else {
System.out.println(this.name + " is already off.");
}
}
public void sleep() {
if (this.isOn) {
System.out.println(this.name + " is going to sleep...");
this.isOn = false;
this.isSleeping = true;
System.out.println(this.name + " is now sleeping.");
} else {
System.out.println(this.name + " is not on.");
}
}
public void wakeUp() {
if (this.isSleeping) {
System.out.println(this.name + " is waking up...");
this.isOn = true;
this.isSleeping = false;
System.out.println(this.name + " is now on.");
} else {
System.out.println(this.name + " is not sleeping.");
}
}
public String getStatus() {
if (this.isOn) {
return this.name + " is on.";
} else if (this.isSleeping) {
return this.name + " is sleeping.";
} else {
return this.name + " is off.";
}
}
}
通过以上代码,我们可以构造一台计算机并进行开机、关机、待机等操作,示例如下:
java
Copy code
Computer myComputer = new Computer("My Computer");
System.out.println(myComputer.getStatus()); // My Computer is off.
myComputer.powerOn(); // Turning on My Computer... My Computer is now on.
System.out.println(myComputer.getStatus()); // My Computer is on.
myComputer.sleep(); // My Computer is going to sleep... My Computer is now sleeping.
System.out.println(myComputer.getStatus()); // My Computer is sleeping.
myComputer.wakeUp(); // My Computer is waking up... My Computer is now on.
System.out.println(myComputer.getStatus()); // My Computer is on.
myComputer.powerOff(); // Turning off My Computer... My Computer is now off.
System.out.println(myComputer.getS
// it分享群:439042787