THINK FIRST·CODE LATER

← All labs

Thermostat: an object that protects its state

Problem

Write a class Thermostat (not public, in the same file) and a public class ThermostatApp.

Thermostat has private fields target (starts at 20) and on (starts true), constants MIN = 10 and MAX = 30, and methods:

method behaviour
boolean setTarget(int t) accepts only MIN..MAX; returns whether it changed
void raise() / void lower() ±1 degree, never leaving the range
void toggle() switches on/off
int getTarget(), boolean isOn() accessors
String toString() Thermostat[ON, target=21]

main reads commands until the end of input: up, down, set 25, power, show. A rejected set prints Rejected: 35 is outside 10..30; an unknown word prints Unknown command: …. At the end print Final: and the thermostat.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l10-2-data-1.txt

show up up show set 35 down power show
What your program must print for l10-2-data-1.txt
Thermostat[ON, target=20]
Thermostat[ON, target=22]
Rejected: 35 is outside 10..30
Thermostat[OFF, target=21]
Final: Thermostat[OFF, target=21]

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l10-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content l10-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.