扫描程序导致空指针异常,但硬编码字符串不会?

时间:2016-03-29 00:11:11

标签: java java.util.scanner

我正在做一项教导我们遵循工厂模式的任务。为此,我编写了一些非常基本的类和子类,只有几个整数字段。在这样做后,我试图看看我是否可以成功实例化这些子类并获取它们的字段。当我传递一个已经硬编码到程序中的字符串时,它工作正常,但是当我尝试通过Scanner传入用户输入时,我得到了一个空指针Exception。我无法弄清楚为什么会导致这种情况?这是我的主要方法:

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;
    }

}

0 个答案:

没有答案