A simple device

Report a typo

Write a class that simulates a simple device. The device has two states: "switched on" and "switched off" and two buttons: "on" and "off". Use the provided template of the Device class and write the code to simulate the following behavior:

  • The initial state of the device is "switched off".
  • When the device is switched off and the "on" button is pressed, print Switching on
  • When the device is switched off and the "off" button is pressed, print Boop!
  • When the device is switched on and the "on" button is pressed, print Beep!
  • When the device is switched on and the "off" button is pressed, print Switching off

Apply the State design pattern to solve this task.

Sample Input 1:

on on off off on

Sample Output 1:

Switching on
Beep!
Switching off
Boop!
Switching on
Write a program in Java 17
import java.util.Scanner;

class Device {

public void switchOn() {

}

public void switchOff() {

}
}

// do not change the code below
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Device device = new Device();
while (scanner.hasNext()) {
if ("on".equals(scanner.next())) {
device.switchOn();
} else {
device.switchOff();
}
}
}
}
___

Create a free account to access the full topic