0

Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.

I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess

I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!

package question;

public class TestShipment {

    public static void main(String[] args) {
   
        Shipment r1 = new Shipment(
            new Parcel("scientific calculator  " , 250),
            new Address("Dubai","05512345678"),
            new Address("Dubai","0505432123"),
            "Salim"
        );
        System.out.println(r1);
        
        Shipment[] arr = new Shipment[100];
        arr[5] = r1;
        
        Shipment[] a = new Shipment[20];
        
        double local = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i].isLocalShipment()) {
                System.out.println(a[i].calcCost());
            }
        }
    }
}
public class Shipment {
    public Parcel item;
    private Address fromAddress;
    private Address toAddress;
    public String senderName;

    public Shipment(Parcel i, Address f, Address t, String name) {
        item = i;
        fromAddress = f;
        toAddress = t;
        senderName = name;
    }

    //setter 
    public void setFromAddress(String c, String p) {
        c =  fromAddress.getCity(); 
        p =  fromAddress.getPhone();
    }

    public boolean isLocalShipment() {
        boolean v = false;
        if (fromAddress.getCity() == toAddress.getCity()) {
            v = true;
        } else {
            v = false;
        }
        return v;
    }

    public double calcCost() {
        double cost = 0;
        if (fromAddress.getCity() == toAddress.getCity()) {
            cost = 5;
        } else {
            cost = 15;
        }
        if(item.weight > 0 && item.weight <= 200) {
            cost += 5.5;
        }
        if(item.weight > 200) {
            cost += 10.5;
        }
        return cost = cost * (1 + 0.5); //fix the tax 
    }

    public String toString() {
        return "From: " + senderName + "\nTo: " + toAddress 
            + "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
    }
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
O H
  • 3
  • 3
  • `if (a[i].isLocalShipment()) { local += [i].calcCost(); }` – 001 Oct 19 '21 at 15:57
  • 1. You get `NullPointerException` in `a[i].isLocalShipment()` -- array `a` is empty and contains only `null` values. In array `arr` only one element is populated. Do you need to get the cost only for `r1`? 2. In setter `setFromAddress` nothing is saved. 3. Strings have to be compared using [`equals` NOT `==`](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Nowhere Man Oct 19 '21 at 16:53

0 Answers0