0

我遇到了一个程序问题,该程序需要我比较对 Date 对象的引用。该场景是一个车辆陈列室,车辆存储在一个数组列表中。

我有一个车辆类

    import java.text.DecimalFormat;
    import java.util.*;
    import java.util.Date;

    public class Vehicle {

private String manufacturer;
private String model;
//private String customerNameSold = null;
private String vehicleID_VIN;
private String dateManufacture;
private String dateSold;

private boolean beenSold;

private char taxBand_A_M;

private double vehicleCost;
private String emissions;



private Customer customerNameSold;
private Date dom;
//private String manuDate;
private Date saleDate;

     //Constructor 7
     public Vehicle (String manu, String mod, String vin, String dateManu, char tax, double cost){

    manufacturer = manu;
    model = mod;
    vehicleID_VIN = vin;
    dateManufacture = dateManu;
    //Add String to Date
    dom = new Date(dateManu);
    taxBand_A_M = tax;
    vehicleCost = cost;
    dateSold = null;
    customerNameSold = null;

    beenSold = false;
}




public String toString() {

    DecimalFormat df = new DecimalFormat("#.00");

    //method calls - do they need this. then method call?
    String s = "\nManufacturer: " + getManu()
            + " \nModel: " + getModel()
            + " \nVIN: " + getVin()
            + " \nDate of Manufacture: " + getManuDate()
            + " \nDate of Manufacture (String to Date): " + getManuDate2()
            + " \nAge of Vehicle: " + getAgeOfVehicle() + " (in WEEKS)"
            + " \nTax Band: " + getTax()
            + " \nEmissions: " + cO2()
            + " \nCost: £" + df.format(getCost())
            + " \nHas Vehicle Been Sold: " + getBeenSold()
            + " \nCustomer: " + getCust()
            + " \nDate Sold: " + getDateSold()
            + " \nDate Sold (String to Date): " + getDateSold2();


    return s;

}

public String getManu() {

    return manufacturer;
}

public String getModel() {

    return model;
}

    ////    public String getCust() {
    ////    
    ////        return customerNameSold;
    ////    }

public Customer getCust() {

    return customerNameSold;
}

public String getVin() {

    return vehicleID_VIN;
}

    public String getManuDate(){

    return dateManufacture;
}

public Date getManuDate2() {

    return dom;
}

public String getDateSold(){

return dateSold;

}

public Date getDateSold2() {

    return saleDate;
}


//CONVENTION SUGGESTS SHOULD BE 'isSold()'
public boolean getBeenSold() {

    return beenSold;
}

public char getTax() {


    return taxBand_A_M;
}

public double getCost() {

    //how to format to 2 decimal places?
    return vehicleCost;
}




public void buyVehicle(String sale, Customer cust) {




    customerNameSold = cust;

    //Add String to Date
    saleDate = new Date(sale);
   dateSold = sale;
    beenSold = true;
}

public String cO2() {


    switch (taxBand_A_M) {
        case 'A':
            emissions = "0-100";
            break;
        case 'B':
            emissions = "101-110";
            break;
        case 'C':
            emissions = "111-120";
            break;
        case 'D':
            emissions = "121-130";
            break;
        case 'E':
            emissions = "131-140";
            break;
        case 'F':
            emissions = "141-150";
            break;
        case 'G':
            emissions = "151-160";
            break;
        default:
            emissions = null;
            break;
    }

    return emissions;
}


public int getAgeOfVehicle() {

    Date now = new Date();
    long diff = now.getTime() - dom.getTime();

    long age = (diff / (1000L * 60 * 60 * 24 * 7));
    return (int) age;
}

}

陈列室课

    import java.util.*;

    public class Showroom {

private String showroomName;
private ArrayList<Vehicle> theVehicles;
private Vehicle currVeh = null;
private ArrayList<Vehicle> recentlySold;
private Date dateSold;

private long diff;
private long age;


      //Constructor Method - Takes the name of the Showroom Object & Creates the array list of vehicles
      public Showroom(String name) {
      showroomName = name;
      theVehicles = new ArrayList<Vehicle>();
      }

public String getName() {
    return showroomName;
}

public void setName(String name) {
    //this.showroomName if passed in parameter was named showroomName also
    showroomName = name;
}

    public boolean addVehicle(Vehicle newVehicle) {


    theVehicles.add(newVehicle);
    currVeh = newVehicle;
    return true;


}

public boolean addVehicleAfterCurrent(Vehicle newVehicle) {


    theVehicles.add(theVehicles.indexOf(currVeh) + 1, newVehicle);
    currVeh = newVehicle;
    return true;


}


public Vehicle findVehicle(String vehicleVIN) {
    for (Vehicle v : theVehicles) {
        if (v.getVin().equalsIgnoreCase(vehicleVIN)) {
            System.out.println("Vehicle Found:\n"
                    + v.getManu() + "\n"
                    + v.getModel() + "\n"
                    + v.getVin() + "\n"
                    + theVehicles.indexOf(v) + "\n");
            return v;

            //OR CALL THE toString() METHOD - v.toString()
        }
    }

    System.out.println("Sorry - The Vehicle was not found in the Showroom!\n"
            + theVehicles.indexOf(vehicleVIN) + "\n");

    return null;
}

public Vehicle setCurrentVehicle(Vehicle cv) {

    currVeh = cv;
    return currVeh;
}

public Vehicle getCurrentVehicle() {
    System.out.println("\nCurrentVehicle: " + currVeh);
    return currVeh;
}

public Vehicle nextVehicle() {


    int index = theVehicles.indexOf(currVeh);
    if (index < 0 || index + 1 == theVehicles.size()) {
        System.out.println("\nEnd of the list");
        return null;
    }
    Vehicle v = theVehicles.get(index + 1);
    setCurrentVehicle(v);
    System.out.println("\nThe Former Next Vehicle & Now Current Vehicle: " + v);


    return currVeh;
}

public Vehicle previousVehicle() {

    int index = theVehicles.indexOf(currVeh);
    if (index <= 0) {
        System.out.println("\nNegative Index -1 Before Start of List");
        return null;
    }
    Vehicle v = theVehicles.get(index - 1);
    setCurrentVehicle(v);
    System.out.println("\nThe Former Previous Vehicle & Now Current Vehicle: " + v);


    return currVeh;

}

public void outputArray() {
    for (Vehicle nextVehicle : theVehicles) {
        System.out.println(nextVehicle.getModel() + "\n" + theVehicles.indexOf(nextVehicle));
    }
}


public void outputShowroomDetails() {
    System.out.println("\nSHOWROOM NAME: " + showroomName);
    //output each vehicle in turn
    System.out.println("THE VEHICLES IN THE SHOWROOM:");
    if (theVehicles.isEmpty()) {
        System.out.println("\n*** There are no Vehicles in the Showroom! ***");
    } else {
        for (Vehicle nextVehicle : theVehicles) {
            System.out.println(nextVehicle.toString() + "\n" + theVehicles.indexOf(nextVehicle));
        }
    }

}

public Vehicle setCurrentVehicleByVIN(String vin) {


    System.out.println("\n*** ATTEMPTING TO SET CURRENT VEHICLE BY VIN:\n"
            + vin);
    Vehicle v = findVehicle(vin);
    if (v != null) {
        System.out.println("\nTHE CURRENT VEHICLE: " + "\nARRAY LIST INDEX: " + theVehicles.indexOf(v)
                + v.toString());
    }
    currVeh = v;
    return currVeh;
}


public boolean deleteVehicle(String vin) {
    System.out.println("\nATTEMPTING TO DELETE VEHICLE:\n"
            + "VEHICLE VIN to DELETE: " + vin);
    Vehicle v = findVehicle(vin);
    if (v != null) {
        theVehicles.remove(v);
        System.out.println("VEHICLE *** " + vin + " *** REMOVED!");
        return true;
    }
    return false;
}

//Method not working - null pointer 'long diff' line
public ArrayList<Vehicle> getVehiclesSoldRecently() {

    recentlySold = new ArrayList<Vehicle>();


    //Each vehicle has a sale date
    //Determine the difference between sale date & todays date
    //If the difference is greater than 14 days (2 weeks)  it won't be added to the array
    //If the difference is less than or equal to 14 days (2 weeks), then they will be added to the array



    if (theVehicles.isEmpty()) {
        System.out.println("\n*** The Showroom is Empty!***");
    } else 
    {
        for (Vehicle v : theVehicles) {

            Date now = new Date();




            dateSold = v.getDateSold2();


            long diff = now.getTime() - v.getDateSold2().getTime();
            long age = (diff / (1000L * 60 * 60 * 24 * 7));


            if (age <= 2) {

                recentlySold.add(v);
                System.out.println("\nVEHICLES RECENTLY SOLD: " + v.toString());
            }

        }
    return recentlySold;

    }


}

&一个客户类

    public class Customer {

private String custName = null;
private String custPhone = null;
private String custEmail = null;

public Customer() {
}

public Customer(String name) {

    custName = name;
    custPhone = "n/a";
    custEmail = "n/a";

}

public Customer(String name, String phone) {

    custName = name;
    custPhone = phone;
    custEmail = "n/a";

}

//***CAN'T HAVE A CONSTRUCTOR DETAILING NAME & EMAIL ONLY
//AS A (String, String) CONSTRUCTOR ALREADY DEFINED
public Customer(String name, String phone, String email) {

    custName = name;
    custPhone = phone;
    custEmail = email;

}

//***AUTO GENERATED GETTERS & SETTERS - this.*
public String getCustName() {
    return custName;
}

public void setCustName(String custName) {
    this.custName = custName;
}

public String getCustPhone() {
    return custPhone;
}

public void setCustPhone(String custPhone) {
    this.custPhone = custPhone;
}

public String getCustEmail() {
    return custEmail;
}

public void setCustEmail(String custEmail) {
    this.custEmail = custEmail;
}

//***AUTO GENERATED TOSTRING METHOD (THOUGH EDITED FOR FORMAT)
@Override
public String toString() {
    String cust = "\n*** CUSTOMER ***"
            + "\nName: " + getCustName()
            + "\nPhone: " + getCustPhone()
            + "\nEmail: " + getCustEmail();

    //System.out.println(cust);

    return cust;
}

}

ShowroomDriver 是

    public class ShowroomDriver {

public static void main(String args[]) {

    Showroom showDrive = new Showroom("ShowroomDriver Showroom");

    System.out.println("\n*** OUTPUT SHOWROOM DETAILS ***");

    showDrive.outputShowroomDetails();

    System.out.println("\n*** CREATE / ADD 4 VEHICLES ***");

    Vehicle sdv1 = new Vehicle("Audi", "R8 Spider", "FAVE 101", "MAR-04-2011", 'E', 45000);
    //Vehicle sdv1 = new Vehicle("Audi", "R8 Spider", "FAVE 101", 03 / 04 / 2011, 'E', 45000);
    System.out.println("\nTesting toString: " + sdv1.toString());

    Vehicle sdv2 = new Vehicle("Tesla", "Model S", "ELEC TRIC", "JAN-01-2013", 'A', 55000);
    //Vehicle sdv2 = new Vehicle("Tesla", "Model S", "ELEC TRIC", 01 / 01 / 2013, 'A', 55000);
    System.out.println("\nTesting to String: " + sdv2.toString());

    Vehicle sdv3 = new Vehicle("Ford", "Cortina", "1212 NUM", "JUN-06-2006", 'D', 55000);
    //Vehicle sdv3 = new Vehicle("Ford", "Cortina", "1212 NUM", 06 / 06 / 2006, 'D', 55000);
    System.out.println("\nTesting to String: " + sdv3.toString());

    Vehicle sdv4 = new Vehicle("VW", "Golf MK 1", "DUB DUB", "NOV-11-1971", 'E', 25000);
    //Vehicle sdv4 = new Vehicle("VW", "Golf MK 1", "DUB DUB", 11/11/1971, 'E', 25000);
    System.out.println("\nTesting to String: " + sdv4.toString());

    showDrive.addVehicle(sdv1);
    showDrive.addVehicle(sdv2);
    showDrive.addVehicle(sdv3);
    showDrive.addVehicle(sdv4);


    System.out.println("\n*** OUTPUT SHOWROOM DETAILS ***");

    showDrive.outputShowroomDetails();

    System.out.println("\n*** BUY 2 VEHICLES ***");

    Customer cust1 = new Customer("Andrew Antivan", "01785 111 111");
    Customer cust2 = new Customer("Belinda Belle", "01782 222 222", "belbel@gmail.com");

    sdv1.buyVehicle("JUL-07-2013", cust1);
    sdv2.buyVehicle("MAR-01-2013", cust2);

    showDrive.outputShowroomDetails();

    System.out.println("\n***CREATE 4 VEHICLES ***");

    Vehicle purV1 = new Vehicle("Ford", "Fiesta", "NAT NAT", "MAR-09-2006", 'E', 5000);
    Vehicle purV2 = new Vehicle("Vauxhall", "Corsa", "LEE 123", "JUL-07-2011", 'D', 5500);
    Vehicle purV3 = new Vehicle("Toyota", "Aygo", "JOHN 32A", "FEB-02-2010", 'E', 2000);
    Vehicle purV4 = new Vehicle("Marvel", "Bat Mobile", "KA BOOM", "MAR-11-2008", 'C', 3000);

    System.out.println("\n*** SELL 2 of 4 VEHICLES ***");




    System.out.println("\n*** ADD THE 4 NEW VEHICLES TO SHOWROOM ***");

    showDrive.addVehicle(purV1);
    showDrive.addVehicle(purV2);
    showDrive.addVehicle(purV3);
    showDrive.addVehicle(purV4);



     purV1.buyVehicle("DEC-12-2012", cust1);
    purV2.buyVehicle("DEC-12-2012", cust1);
    purV3.buyVehicle("OCT-18-2013", cust2);
    purV4.buyVehicle("OCT-19-2013", cust2);

            showDrive.outputShowroomDetails();

            showDrive.getVehiclesSoldRecently();




}

}

程序被逐步修改。最初制造和销售的日期是作为字符串对象传入(硬编码)的,但现在它们必须作为日期对象添加。

我遇到的问题仅在我尝试调用 getVehiclesSoldRecently() 方法时才发生。我收到一个空指针异常警告,这表明问题是由于该方法中的“差异...”行而发生的。

收到的错误:

线程“主”java.lang.NullPointerException 中的异常

在 Showroom.getVehiclesSoldRecently(Showroom.java:197)

    diff=now.getTime()-v.getDateSold2().getTime();

在 ShowroomDriver.main(ShowroomDriver.java:93)

    showDrive.getVehiclesSoldRecently();

任何帮助指出我哪里出错了,我们将不胜感激。

谢谢。

* 编辑 *

除 getDates 之外的所有方法的方法签名都必须保持不变,这意味着必须将 String 参数传入 & 然后转换为 Date 对象。

4

1 回答 1

1

代表着:

v.getDateSold2()

返回null

diff=now.getTime()-v.getDateSold2().getTime();

所以你实际上做的是调用getTime()空对象。v.getDateSold2()在尝试访问它之前,您需要检查是否为 null。

如果它为空,您可以忽略它或打印其他内容。

于 2013-10-22T07:55:02.473 回答