The class shown below keeps track of a pressure sensor in a laboratory. When a Sensor object is created using the first constructor, the initial pressure is set to zero. When it is created using the second constructor it is set to the value of the parameter. The pressure should not be set to a value less than zero. Therefore, if the input parameter to the setPressure method is a negative number, the pressure should not be changed and a value of false should be returned. If the pressure is set successfully, a value of true should be returned. (a) Write the code for the Sensor class. (b)
class Sensor {
private int pressure;
public Sensor() {
}
public Sensor(int pressure) {
if (!setPressure(pressure)) {
System.out.println("Pressure is a negative number");
}
}
/**
* @return the pressure
*/
public int getPressure() {
return pressure;
}
/**
* @param pressure the pressure to set
*/
public boolean setPressure(int pressure) {
if (pressure >= 0) {
this.pressure = pressure;
return true;
}
return false;
}
}
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Sensor sensor = new Sensor();
if (!sensor.setPressure(45)) {
System.out.println("Pressure is a negative number");
} else {
System.out.println("Sensor pressure: " + sensor.getPressure());
}
if (!sensor.setPressure(-45)) {
System.out.println("Pressure is a negative number");
} else {
System.out.println("Sensor pressure: " + sensor.getPressure());
}
}
}
Comments
Leave a comment