Exercise 1 w/ solution

25/07/2009 09:13

Classes – Part I

Vehicle
+load : double
+maxLoad : double
+Vehicle(max_Load : double)
+getLoad( ) : double
+getMaxLoad( ) : double


1. Create a class Vehicle that implements the above UML diagram.
a. Include two public attributes: load “the current weight of the vehicle’s cargo” and maxLoad “the vehicle’s maximum cargo weight limit.
b. Include one public constructor to set the maxLoad attribute.
c. Include two public access methods: getLoad to retrieve the load attribute and getMaxLoad to return the maxLoad attribute.

All of the data is assumed to be in kilograms.

TestVehicle.java
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.load = vehicle.load + 500.0;

System.out.println("Add box #2 (250kg)");
vehicle.load = vehicle.load + 250.0;

System.out.println("Add box #3 (5000kg)");
vehicle.load = vehicle.load + 5000.0;

System.out.println("Add box #4 (4000kg)");
vehicle.load = vehicle.load + 4000.0;

System.out.println("Add box #5 (300kg)");
vehicle.load = vehicle.load + 300.0;

// Print out the final vehicle load
System.out.println("Vehicle load is " + vehicle.getLoad() + " kg");
}
}

2. Read the TextVehicle.java code. The program gets into trouble when the last box is added to the vehicle’s load because the code does not check if adding this box exceeds the maxLoad.
3. Compile the Vehicle and TestVehicle classes.
4. Run the TestVehicle class. The output generated should be:

Creating a vehicle with a 10,000kg maximum load.
Add box #1 (500kg)
Add box #2 (250kg)
Add box #3 (5000kg)
Add box #4 (4000kg)
Add box #5 (300kg)
Vehicle load is 10050.0 kg.

 

 

Solution:

public class Vehicle
{
public double load=0;
public double maxload=0;

public Vehicle(double maxload){


}
public double getLoad()
{
return load;
}

public double getMaxLoad()
{
return maxload;
}

}

//-----end------

Back