Exercise 2 w/ Solution
25/07/2009 14:30
Vehicle |
-load : double -maxLoad : double |
+Vehicle(max_Load : double) +getLoad( ) : double +getMaxLoad( ) : double +addBox(weight : double) :boolean |
- To solve the problem from the previous exercise, you hide the internal data(load and maxLoad) and provide a method, addBox, to perform the proper checking that the vehicle is not being overloaded.
- Copy your code from the last exercise, and modify if to implement the Vehicle class as shown in the above UML diagram.
- Modify the load and maxLoad attributes to be private.
- Add the addBox method. This method takes a single argument, which is the weight of the box in kilograms. The method must verify that adding the box will not violate the maximum load. If a violation occurs, the box is rejected by returning the value of false; otherwise the weight of the box is added to the vehicle load and the method returns true.
Hint: You must use an “if” statement. Here is the basic form f the conditional form:
If (
} else {
}
All of the data is assumed to be in kilograms.
- Read the TestVehicle.java code. The code cannot modify the load attribute directly, but now must use the addBox method. This method returns a true or false value, which is printed to the screen.
- Compile the Vehicle and TestVehicle classes.
- Run the TestVehicle class. The output generated should be:
Creating a vehicle with a 10,000kg maximum load.
Add box #1 (500kg) : true
Add box #2 (250kg) : true
Add box #3 (5000kg) : true
Add box #4 (4000kg) : true
Add box #5 (300kg) : false
Vehicle load is 9750.0 kg.
SOLUTION:
TestVehicle Part.
public class TestVehicle {
public static void main(String[] args) {
// Create a vehicle that can handle 10,000 kilograms weight
System.out.println("Creating a vehicle with a 10,000kg maximum load.");
Vehicle vehicle = new Vehicle(10000.0);
// Add a few boxes
System.out.println("Add box #1 (500kg) : " + vehicle.addBox(500.0));
System.out.println("Add box #2 (250kg) : " + vehicle.addBox(250.0));
System.out.println("Add box #3 (5000kg) : " + vehicle.addBox(5000.0));
System.out.println("Add box #4 (4000kg) : " + vehicle.addBox(4000.0));
System.out.println("Add box #5 (300kg) : " + vehicle.addBox(300.0));
// Print out the final vehicle load
System.out.println("Vehicle load is " + vehicle.getLoad() + " kg");
}
}
----end---
Vehicle Part.
public class Vehicle {
private double load, maxload;
public Vehicle ( double max_load){
maxload = max_load;
}
public double getLoad () {
return load;
}
public double getMaxLoad(){
return maxload;
}
public boolean addBox(double weight)
{
if( load + weight >= maxload ){
return true;
} else {
load = load + weight;
return false;
}
}
}
----end---
———
Back