0

I'm working on an assignment that is teaching us to follow the factory patter. To do this I coded up some very basic classes and sub classes with only a few integer fields. After doing so I tried to see if I could successfully instantiate those sub-classes and get their fields. It worked fine when I passed a string that had been hard coded into the program, but when I tried to pass in user input via Scanner I got back a null pointer Exception. I cant figure out why, what would cause this? Here is my main method:

public static void main(String args[])
{
    VehicleFactory vf = new VehicleFactory();
    VehicleClass vc = null;
    Scanner sc = new Scanner(System.in);
    String type = null; 

    //this works
    type = "car";
    vc = vf.createVehicle(type);
    System.out.println(vc.getEngineAmt());

    //this throws and exception 
    //I even did a string cmp between sc.nextLine() and "car" for my sanity
    //And the reurn was 0
    vc = vf.createVehicle(sc.nextLine());
    System.out.println(vc.getEngineAmt());

    sc.close();

}

public class VehicleClass {

private int WheelAmt = 0;
private int EngineAmt = 0;


public int getWheelAmt() {
    return WheelAmt;
}
public void setWheelAmt(int wheelAmt) {
    WheelAmt = wheelAmt;
}
public int getEngineAmt() {
    return EngineAmt;
}
public void setEngineAmt(int engineAmt) {
    EngineAmt = engineAmt;
}

public class VehicleFactory {

    public VehicleClass createVehicle(String type){

        VehicleClass createdVehicle = null;

        System.out.println(type);

        if(type == "car")
        {
            createdVehicle = new Car();
        }else if(type == "boat")
        {
            createdVehicle  = new Boat();
        }else if(type == "plane"){
            createdVehicle = new Plane();
        }


        return createdVehicle;
    }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

0 Answers0