Photo AI
Question 3
Smart switches have been installed to monitor and automate name devices. The program to be developed will determine the device power usage of the switch and the user... show full transcript
Step 1
Answer
In the SmartSwitch class, define a method called energyUsed(int hours)
that calculates the energy consumption
using the formula provided:
public double energyUsed(int hours) {
return (powerUsage * hours) / 1000.0;
}
This method accepts the number of hours the device has been powered on and returns the energy used in kilowatt-hours (kWh).
Step 2
Answer
The setSwitchStatus
method will set the device's switch status. Define it as follows:
public void setSwitchStatus(boolean status) {
this.fSwitchStatus = status;
}
This method will receive a Boolean value, setting the switch status accordingly.
Step 3
Answer
Define the toString
method to return a formatted string of all object attributes:
@Override
public String toString() {
return String.format("Switch ID: %s\nDevice: %s\nPower usage: %s\nPower status: %s",
fSwitchID, fDeviceName, fPowerUsage, determineSwitchStatus());
}
Here, determineSwitchStatus()
checks if the device is ON or OFF.
Step 4
Answer
To extract the switchID from the combo box cmbQ3_2_1 and instantiate the SmartSwitch object, write:
// Extract switch ID
String switchID = (String) cmbQ3_2_1.getSelectedItem();
// Extract the selected device and power usage
String selectedDevice = lstQ3_2_1.getSelectedValue();
String[] parts = selectedDevice.split(" ");
String device = parts[0];
int powerUsage = Integer.parseInt(parts[1]);
// Instantiate the SmartSwitch object
SmartSwitch objSmartSwitch = new SmartSwitch(switchID, device, powerUsage);
This initializes the SmartSwitch
object with the proper attributes.
Step 5
Answer
To change the switch status based on the selection from the radio group, implement:
boolean status = radioGroup.isSelected() ? true : false;
objSmartSwitch.setSwitchStatus(status);
// Display the ID and status
String switchStatus = objSmartSwitch.determineSwitchStatus();
richEdit.setText(String.format("%s, %s", switchID, switchStatus));
This updates the switch status and shows it in the rich edit.
Step 6
Answer
To write a date-time entry in log.txt
, the following code should be used:
FileWriter writer = new FileWriter("log.txt", true);
writer.write(String.format("%s, %s, %s, %s\n",
DateToStr(new Date()),
getCurrentTime(),
objSmartSwitch.getSwitchID(),
objSmartSwitch.determineSwitchStatus()));
writer.close();
This appends the required information into the log file.
Step 7
Answer
For the power usage calculation, use:
int hours = Integer.parseInt(edtQ3_2_4.getText().toString());
double energyUsed = objSmartSwitch.energyUsed(hours);
// Display the result
richEdit.setText(String.format("Energy used: %.2f kWh", energyUsed));
This retrieves the user-inputted hours and displays the energy used in kilowatt-hours.
Report Improved Results
Recommend to friends
Students Supported
Questions answered