Java覆盖超类方法空例外

时间:2016-11-15 05:42:50

标签: java inheritance methods nullpointerexception override

我很难找到为什么我的代码在从子类运行getScale()方法时显示空指针异常错误"天气"。子类中的getScale方法假设根据短格式将私有变量(缩放)更改为长格式(返回Celcius而不是C)。

* PS这是学校计算机科学的继承练习

感谢您的反馈。

主要方法

    Temperature number = new Temperature ();
    Temperature scale = new Temperature ();

    System.out.print ("Enter temperature: ");
    number.setNumber (Double.parseDouble (stdin.readLine ()));
    System.out.print ("Enter scale (C/F/K): ");
    scale.setScale (stdin.readLine ());

    Weather windSpeed = new Weather ();
    Weather windDirection = new Weather ();
    Weather visibility = new Weather ();

    System.out.print ("Enter wind speed (km/h): ");
    windSpeed.setWindSpeed (Double.parseDouble (stdin.readLine ()));
    System.out.print ("Enter wind direction: ");
    windDirection.setWindDirection (stdin.readLine ());
    System.out.print ("Enter visibility (m): ");
    visibility.setVisibility (Double.parseDouble (stdin.readLine ()));

    System.out.println ("\nTemperature: " + number.getNumber () + " " + scale.getScale ());
    System.out.println ("Wind Speed: " + windSpeed.getWindSpeed () + " km/h");
    System.out.println ("Wind Direction: " + windDirection.getWindDirection ());
    System.out.println ("Visibility: " + visibility.getVisibility () + " m");

    Temperature scaleFull = new Weather ();

    System.out.println ("\nTemperature: " + number.getNumber () + " " + scaleFull.getScale ());
    System.out.println ("Wind Speed: " + windSpeed.getWindSpeed () + " km/h");
    System.out.println ("Wind Direction: " + windDirection.getWindDirection ());
    System.out.println ("Visibility: " + visibility.getVisibility () + " m");

温度等级(超类)

private double number;
private String scale;   

public void setNumber (double number)
{
    this.number = number;
}


public double getNumber ()
{
    return number;
}


public void setScale (String scale)
{
    this.scale = scale;
}


public String getScale ()
{
    return scale;
}

天气等级(子类扩展温度)

 private double windSpeed;
private String windDirection;
private double visibility;

public void setWindSpeed (double windSpeed)
{
    this.windSpeed = windSpeed;
}


public void setWindDirection (String windDirection)
{
    this.windDirection = windDirection;
}


public void setVisibility (double visibility)
{
    this.visibility = visibility;
}


public double getWindSpeed ()
{
    return windSpeed;
}


public String getWindDirection ()
{
    return windDirection;
}


public double getVisibility ()
{
    return visibility;
}


public String getScale ()
{
    if ((super.getScale ()).equals ("C"))
    {
        return ("Celcius");
    }
    else if ((super.getScale ()).equals ("F"))
    {
        return ("Fahrenheit");

    }
    else if ((super.getScale ()).equals ("K"))
    {
        return ("Kelvin");
    }

    return (" units");

}

0 个答案:

没有答案