我正在尝试创建一个保存位置的类,包括以下方法:
每个数据字段的 setter (修改器) 对于位置名称,您应该使用trim() 方法删除任何前导或尾随空格。
每个数据字段的 getter (访问器)
构造函数:您应该只有一个获取地名、纬度和经度的构造函数。尽管可能需要修剪字符串,但您可能期望数据有效。
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;
}
}
我不确定我哪里出了问题,两个城市、两个纬度和两个经度都出现错误。这是我第一次写类(class),所以请帮我简化所有内容。感谢您抽出时间。
最佳答案
你就快到了。你有:
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;
}
...
}
查看 declaring member variables 上的官方教程。它简洁且写得很好,可以让您更好地了解正在发生的事情。
关于Java:Getter、Setter 和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419349/