java如何在主语句中将对象连接在一起?
我教AP CSA(第一年),并决定给我的孩子一个具有挑战性的(至少对我来说)任务。他们应该用打印的语句来告诉一个恶棍走一段特定的距离需要多长时间。在我给他们之前,我想有一个解决方案
print语句对我来说很简单,程序“按预期”工作——我忍不住认为我把它弄得太复杂了,失去了一个机会来抽象一点,而不是硬编码我的经度和纬度。有没有更好的方法将地理定位开始和地理定位结束对象连接到我的城市?请参阅下面的代码
GeoLocation start = new GeoLocation(37.765469, 100.015167);
GeoLocation end = new GeoLocation(37.275280, 107.880066);
double distance = start.distanceFrom(end);
double travelTime = distance/15;
int travelReport = (int)travelTime;
WesternTown sweatyPost = new WesternTown();
sweatyPost.saloons = 2;
sweatyPost.sheriffs = 1;
sweatyPost.troublemakers = 5;
WesternTown dodgeCity = new WesternTown();
dodgeCity.saloons = 7;
dodgeCity.sheriffs = 2;
dodgeCity.troublemakers = 29;
dodgeCity.longitude = 100.015167;
dodgeCity.latitude = 37.765469;
WesternTown durango = new WesternTown();
durango.saloons = 4;
durango.sheriffs = 0;
durango.troublemakers = 6;
durango.longitude = 107.880066;
durango.latitude = 37.275280;
# 1 楼答案
可以将
GeoLocation
视为WesternTown
的属性,因此它可以是一个属性:你会有
在GeoLocation类中保留方法
或者搬到威斯顿
# 2 楼答案
将私有
GeoLocation
属性添加到WesternTown
,并创建公共方法setLocation(GeoLocation location)
来设置位置。这将使您受益于在GeoLocation
内完成的任何验证,并且不需要自己设置lat和long然后你可以简单地说
dodgeCity.setLocation(start)
和durango.setLocation(end)
或者更好的方法是,在构造函数中包含
GeoLocation
,然后完全不需要setter。这是更好的选择,因为一个城镇一旦建成,就无法改变其位置,这真的毫无意义如果按此路线执行,请删除默认构造函数(如果有),以确保创建的所有城镇都有一个位置
现在,您可以轻松计算任意两个城市之间的距离:
另外,虽然不完全重要,但您可能应该将其他字段设置为私有,并为它们包含setter/getter。这是更多的代码,但它促进了更好的实践,并让他们习惯了调用方法与对象状态交互的想法