Create a delivery class for a delivery service. The class contains fields to hol
ID: 3531018 • Letter: C
Question
Create a delivery class for a delivery service. The class contains fields to hold the following: - A deliver number that contains 8 digits. the first four digits represent the year, and the last four digits represent the delivery number. For ex, the 76th delivery in 2011 has a complete delivery number of 20110076. - A code representing the delivery area. A local delivery is code 1, and a long distance delivery is a code 2. -A weight, in pounds, of the item to be delivered, - The fee for the delivery, as follows: Distance Weight Fee($) 1 Under 5 Pounds 12.00 1 5 - 20 lbs 16.50 1 Over 20 lbs 22.00 2 Under 5 lbs 35.00 2 5 lbs or more 47.95Explanation / Answer
class Delivery {
public final static int LOCAL = 1;
public final static int LONG_DISTANCE = 2;
private int year, month, deliveryNum, distance;
private double weight, fee;
private String deliveryCode;
public Delivery() {
}
// Delivery constructor
public Delivery(int year, int month, int deliveryNum, int distance, double weight) {
this.year = year;
this.month = month;
this.deliveryNum = deliveryNum;
this.distance = distance;
this.weight = weight;
this.fee = this.calculateFee(); // set the fee for this delivery
this.deliveryCode = this.getCode();
}
// private utility method to calculate the fee for a delivery based its weight and distance
private double calculateFee() {
if (this.distance == Delivery.LOCAL) {
if (this.weight < 5)
return 12;
if (this.weight >= 5 && this.weight <= 20)
return 16.5;
if (this.weight > 20)
return 22;
}
else if (this.distance == Delivery.LONG_DISTANCE) {
if (this.weight < 5)
return 35;
if (this.weight >= 5)
return 47.95;
}
return -1; // should never be here
}
private String getCode() {
// find the last digit of the year
String yearStr = Integer.toString(this.year);
String lastDigit = yearStr.substring(yearStr.length() - 1);
return String.format("%1$1s%2$02d%3$03d", lastDigit, this.month, this.deliveryNum);
}
// string formats were used for formatting the strings properly details can be found at
//http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
public String toString() {
String str = String.format("%1$-15s %2$-15s ", "Delivery No.", "Fee");
str += String.format("%1$-15s $%2$-4.2f ", this.deliveryCode, this.fee);
return str;
}
public static void main(String[] args) {
// create a few deliveries
Delivery[] deliveries = new Delivery[]{
new Delivery(2001, 3, 76, Delivery.LOCAL, 10.5),
new Delivery(2003, 5, 5, Delivery.LONG_DISTANCE, 3),
new Delivery(2009, 9, 100, Delivery.LOCAL, 9)
};
for (int i=0; i<deliveries.length; ++i) {
System.out.println(deliveries);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.