簡體   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