已完成程序中线程“main”java.lang.NullPointerException中的异常

时间:2012-12-03 22:12:28

标签: java exception

我得到了我认为已经完成的程序,现在java正在把它拉到我身上。

我得到的错误如下:

Exception in thread "main" java.lang.NullPointerException
    at hirecardemo.HireCar.isAvailable(HireCar.java:68)
    at hirecardemo.HireCarDemo.runSimulation(HireCarDemo.java:49)
    at hirecardemo.HireCarDemo.main(HireCarDemo.java:25)
Java Result: 1

主类:

package hirecardemo;
import java.util.Random;

public class HireCarDemo {

    public static void main(String[] args) {
        HireCar car0 = new HireCar("Toyota", "AV77 FGJ", 6000, 12300, 41500);
        HireCar car1 = new HireCar("Mercedes", "DI99 FTZ", 6700, 7000, 91800);
        HireCar car2 = new HireCar("Toyota", "FG82 FTP", 25000, 12000, 72000);
        HireCar car3 = new HireCar("Vauxhall", "TW56 LTS", 10000, 11000, 19001);
        HireCar car4 = new HireCar("Ford", "TD85 LTU", 13000, 12300, 12000);
        HireCar car5 = new HireCar("Susuki", "GU12 UTJ", 12000, 10000, 50000);

        HireCar[] fleet = {car0, car1, car2, car3, car4, car5};
        int minMileage = 1000;
        int maxMileage = 60000;
        int numberOFevents = 12;

        String [] results = HireCarDemo.runSimulation(fleet, numberOFevents,
                minMileage, maxMileage);

        for(int i = 0; i < numberOFevents; i++) {
            System.out.println(results[i]);
        }
    }

    /**
    * @param fleet the fleet of hire cars
    * @param numberOFevents the size of the events table to be generated
    * @param minMileage the assumed minimum mileage driven by any hired
    * car
    * @param maxMileage the assumed maximum mileage driven by any hired
    * car
    * @return table of events generated during the simulation
    */
    public static String[] runSimulation(HireCar [] fleet, int numberOFevents, 
            int minMileage, int maxMileage) {
        int n = fleet.length; // Number of cars in the fleet.
        Random carGenerator = new Random();
        String [] events = new String [numberOFevents];
        for(int i = 0; i < numberOFevents; i++) {
            int randomNumber = carGenerator.nextInt(n-1);
            if(fleet[randomNumber].isAvailable() == true)
            {
                fleet[randomNumber].hireOut();
                events[i] = fleet[randomNumber].getRegNumber() + " <HIRE OUT>";
            }

            else if(fleet[randomNumber].isOnHire() == true)
            {
                Random mileage = new Random();
                int randomMileage = mileage.nextInt(maxMileage - minMileage); 

                if(fleet[randomNumber].isBeingServiced() == true)
                {
                    events[i] = fleet[randomNumber].getRegNumber() + 
                            " <RETURN FROM HIRE>" + " <SEND FOR SERVICE>";
                } else {
                    events[i] = fleet[randomNumber].getRegNumber() + 
                            " <RETURN FROM HIRE>";                    
                }
            }
            else 
            {
                fleet[randomNumber].makeAvailable();
                events[i] = fleet[randomNumber].getRegNumber() + 
                        " <RETURN FROM SERVICE>";
            }
        }
        return events;  
    }
}

这是我的单独课程:

//******************************************************************************
// HireCar.java                                             Author: Ryan Holder
// 
// Represents the car hire company's fleet of cars and the information on them.
//******************************************************************************
package hirecardemo;


public class HireCar {

    private String manufacturer, regNumber, carStatus;
    private int mileage, serviceInterval, lastService; // All in miles.    

    private boolean serviceDue() { 
        if((mileage- lastService) >= serviceInterval) {
            this.sendForService();  
            return true;
        } else { 
            return false;
        }
    }

   private void sendForService() {
       carStatus = "Servicing";      
   }

    //--------------------------------------------------------------------------
    // Default Constructor: Sets information for a new car.
    //--------------------------------------------------------------------------    
    public HireCar(String demoManufacturer, String demoRegNumber) {
        manufacturer = demoManufacturer;
        regNumber = demoRegNumber;
        carStatus = "Available";
        serviceInterval = 0;        
        lastService = 0;
        mileage = 0;                 
    }  

      public HireCar(String demoManufacturer, String demoRegNumber, 
             int demoMileage, int demoServiceInterval, int lastInterval) { 
         manufacturer = demoManufacturer;
         regNumber = demoRegNumber;
         mileage = demoMileage;     
     }

    public void setMileage(int demoMileage) {
        mileage = demoMileage;
    }    

    public void setServiceInterval(int demoServiceInterval) {
        serviceInterval = demoServiceInterval;
    }

    public void setLastService(int demoLastService) {
        lastService = demoLastService;    
    }

    public String getRegNumber() {
        return regNumber;
    }

    public void makeAvailable() {
        carStatus = "Available";
    }


    public boolean isAvailable() {
        if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isOnHire() {
        if(carStatus.equals("On Hire")) {
            return true;
        } else {
            return false;
        }
    }


    public boolean isBeingServiced() {
        if(carStatus.equals("Being Serviced")) {
            return true;
        } else {
            return false;
        }
    }


 public void hireOut() {
        carStatus = "On Hire"; 
    }

    public void returnFromHire() {
        if(this.serviceDue() == true) {
            carStatus = "Being Serviced";            
        } else {
            carStatus = "Available For Hire";
        }        
    }

    public void returnFromService() {
        carStatus = "Return From Service";
    }

    public String ToString() {
        return("Manufacturer: <" + this.manufacturer + ">/n "
                + "Registration Number: <" + this.regNumber + ">/n" 
                + "Mileage: <" + this.mileage + ">/n" 
                + "Service Interval: <" + this.serviceInterval + "</n"
                + "Last Service: <" + this.lastService + "</n"
                + "Status: <" + this.carStatus + "</n");
    }
}

4 个答案:

答案 0 :(得分:2)

您正在使用5-arg constructor构建HireCar个实例: -

new HireCar("Toyota", "AV77 FGJ", 6000, 12300, 41500);

在该构造函数中,您尚未设置 - "carStatus"的值。

 public HireCar(String demoManufacturer, String demoRegNumber, 
         int demoMileage, int demoServiceInterval, int lastInterval) { 
     manufacturer = demoManufacturer;
     regNumber = demoRegNumber;
     mileage = demoMileage;     
 }

因此,carStatus仍为null。 (您应该在此构造函数中设置每个字段。至少references,因为它们的默认值为null

因此,当您为isAvailable中添加的任何实例调用array方法时: -

fleet[randomNumber].isAvailable() 

这将导致NPEisAvailable方法一样,您在equals上调用carStatus方法: -

if(carStatus.equals("Available") || carStatus.equals("Return from Service"))
     ^^^
 This is null here

答案 1 :(得分:1)

stacktrace告诉你isAvailable方法正在抛出NullPointerException,所以让我们看一下。

public boolean isAvailable() {
    if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
        return true;
    } else {
        return false;
    }
}

不必要的返回真/假,此处唯一被解除引用的是汽车状态,那么什么时候可以为空?

好吧,看看你正在使用的构造函数:带有5个参数的构造函数。它从来没有设置状态,因此它保持为空。因此空指针。

答案 2 :(得分:0)

您在具有2-args的构造函数中初始化 carStatus并且您从不调用该构造函数,因此,carStatus在您调用equals()时仍为null在isAvailable()方法中。

if(carStatus.equals(“Available”)|| carStatus.equals(“Return from service”)){

   ^^^ This is **null** as it is not initialized yet, Thus **NPE**.

您还应该在5-args构造函数中初始化carStatus,以使当前代码正常工作。

 public HireCar(String demoManufacturer, String demoRegNumber, 
             int demoMileage, int demoServiceInterval, int lastInterval) { 
         manufacturer = demoManufacturer;
         regNumber = demoRegNumber;
         mileage = demoMileage;     
         carStatus="someval" ; //initialize carStatus here
     }

答案 3 :(得分:0)

  1. 使用枚举代替carStatus的字符串
  2. 初始化所有构造函数中的所有属性(第二个左侧carStatus = null)