どのように私はメインの文の中に一緒にオブジェクトを接続することができますか?

無知AP教師:

私はAP CSA(初年度)を教え、(少なくとも私には)私の子供に挑戦を与えることを決定しました割り当て。彼らは、それが特定の距離を移動するために悪役を取るどのくらい教えてくれますprint文を生成し、使用することになっています。私は、私は彼らにそれを与える前の溶液を持っていると思います。

print文は私のために簡単だったし、プログラムは「意図したとおりに」働く - 私は助けることはできませんが、私はそれがあまりにも複雑で、私の経度と緯度をコード化する抽象A少しの代わりに、ハードに機会を失ったと思います。私は私の都市に開始し、ジオロケーションエンドオブジェクトジオロケーションを接続するための良い方法はありましたか?私のコードは、以下を参照してください。

    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;
azro:

あなたは見ることができるGeoLocationのプロパティとしてWesternTown、それは属性であるcouleので:

public class WesternTown{
    private int saloons;
    private int sheriffs;
    private int troublemakers;
    private GeoLocation location;

    // appropriate constructor with all :
    public WesternTown(int saloons, int sheriffs, int troublemakers, Geolocation location){
        this.saloons = saloons;
        ...
    }
}

そして、あなたが持っているでしょう

WesternTown dodgeCity = new WesternTown(7, 2, 29, new GeoLocation(37.765469, 100.015167));
WesternTown durango = new WesternTown(4, 0, 6, new GeoLocation(37.275280, 107.880066));

// 1. Leave method in GeoLocation class
double distance = dodgeCity.getLocation().distanceFrom(durango.getLocation());
// 2. or move it into WesternTown
double distance = dodgeCity.distanceFrom(durango);

  1. ジオロケーションクラスで残す方法

    double distanceFrom(Geolocation other){
        return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
    }
    
  2. またはWesternTownに移動

    // move all the method
    double distanceFrom(WesternTown other){
        return Math.sqrt(Math.pow(this.location.getX() - other.location.getX(), 2) + 
                         Math.pow(this.location.getY() - other.location.getY(), 2));
    }
    
    // or just call the Geolocation method
    double distanceFrom(WesternTown other){
        return this.location.distanceFrom(other.location);
    }
    

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=237204&siteId=1