繁体   English   中英

Java:获取器,设置器和构造器

[英]Java: Getters, Setters, and Constructor

我正在尝试创建一个包含位置的类,包括以下方法:

每个数据字段的设置器(更改器)对于位置名称,应使用trim()方法删除任何前导或尾随空格。

每个数据字段的获取器(访问器)

构造函数:您只能有一个采用地名,纬度和经度的构造函数。 您可能期望数据将是有效的,尽管可能需要修剪字符串。

public class Location {
    public Location(String aCity, double aLatitude, double aLongitude)
    {
        String city = aCity;
        double latitude = aLatitude;
        double longitude = aLongitude;
    }
    void setLocation(String theCity)
    {
        city = theCity.trim();
    }
    void setLatitude(double lat)
    {
        latitude = lat;
    }
    void setLongitude(double long1)
    {
        longitude = long1;
    }
    public String getLocation()
    {
        return city;
    }
    public double getLatitude()
    {
        return latitude;
    }
    public double getLongitude()
    {
    return longitude;
    }
}

我不确定在这里哪里出错了,在两个城市,两个纬度和两个经度上都出现了错误。 这是我第一次上课,所以请为我哑巴。 谢谢你的时间。

你快到了。 你有:

public Location(String aCity, double aLatitude, double aLongitude)
{
    String city = aCity;
    double latitude = aLatitude;
    double longitude = aLongitude;
}

您在构造函数中声明局部变量。 您实际上想声明字段:

public class Location {

    private String city;
    private double latitude;
    private double longitude;

    public Location(String aCity, double aLatitude, double aLongitude)
    {
        city = aCity;
        latitude = aLatitude;
        longitude = aLongitude;
    }

    ...

}

查看有关声明成员变量的官方教程。 它简洁明了,写得很好,可以让您更好地了解正在发生的事情。

这是您做错的事情:

在代码中,您可以在构造函数中声明变量。 这将使它们仅对构造函数可见。 而不是像这样:

public class Location {
    public Location(String aCity, double aLatitude, double aLongitude)
    {
        String city = aCity;
        double latitude = aLatitude;
        double longitude = aLongitude;
    }
    void setLocation(String theCity)
    {
        city = theCity.trim();
    }
    void setLatitude(double lat)
    {
        latitude = lat;
    }
    void setLongitude(double long1)
    {
        longitude = long1;
    }
    public String getLocation()
    {
        return city;
    }
    public double getLatitude()
    {
        return latitude;
    }
    public double getLongitude()
    {
    return longitude;
    }
}

您的代码应如下所示:

public class Location {

    String city = null;
    double latitude;
    double longitude;

    public Location(String aCity, double aLatitude, double aLongitude)
    {
        city = aCity;
        latitude = aLatitude;
        longitude = aLongitude;
    }
    void setLocation(String theCity)
    {
        city = theCity.trim();
    }
    void setLatitude(double lat)
    {
        latitude = lat;
    }
    void setLongitude(double long1)
    {
        longitude = long1;
    }
    public String getLocation()
    {
        return city;
    }
    public double getLatitude()
    {
        return latitude;
    }
    public double getLongitude()
    {
        return longitude;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM