且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:Getters,Setters和Constructor

更新时间:2022-10-14 23:34:58

您几乎就在那里。您有:

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

...

}


$ b b

查看有关声明成员变量的官方教程。它是简洁和写好的,将让你更好地了解发生了什么。


I'm trying to Create a class that holds a location,Including the following methods:

Setters (mutators) for each of the data fields For the location name, you should use the trim() method to remove any leading or trailing blank spaces.

Getters (accessors) for each of the data fields

Constructor: You should have only one constructor that takes the place name, the latitude, and the longitude. You may expect that the data will be valid, although the strings may need to be trimmed.

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

I'm not sure where I'm going wrong here, I'm getting errors on both citys, both latitudes, and both longitudes. This is my first time writing a class, so please dumb everything down for me. Thanks for your time.

You are almost there. You have:

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

You are declaring local variables in the constructor. You actually want to be declaring fields:

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

    ...

}

Check out the official tutorial on declaring member variables. It is concise and well-written and will give you a better idea of what is going on.