2015-08-21 17 views
0

我使用location.speed()函數從GPS獲取我的速度,並將值存儲在nCurrentSpeed中。 我應該將nCurrentSpeed值存儲在數組中以獲得應用程序停止時的平均速度嗎?我該怎麼做?將變量值存儲在數組中以查找平均速度

@Override 
public void onLocationChanged(Location location) { 
    TextView dis =(TextView)findViewById(R.id.distance); 
    TextView time1 =(TextView)findViewById(R.id.time); 
    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "SPEEDOFONT.TTF"); 
    text2 = (TextView) findViewById(R.id.text2); 
    text2.setTypeface(myTypeface); 
    float speed,time, distance; 
    if (location == null) { 
     text2.setText("-.- km/h"); 
    } else { 
     float nCurrentSpeed = location.getSpeed(); 
     speed = (float) (nCurrentSpeed * 3.6); 
     text2.setText(String.format("%.2f km/h", speed)); 

     time =location.getTime(); 


     time1.setText("" +time); 

     distance = speed*time; 
     dis.setText(String.format("%.2f m/s", distance)); 
    } 

} 
+0

你應該?我不知道。你在做什麼?如果最終只想知道平均速度,只需保持平均值始終保持最新......'average =((average *(numberOfPoints - 1))+ currentSpeed)/ numberOfPoints; ' –

+0

您想要整個旅程的平均值,還是隻想在最後x秒/分鐘/小時內的平均值? – Simon

+0

我實際上想要使用停止按鈕結束整個旅程的平均速度。 –

回答

1

它可能不被察覺到實際的(非常具體)的問題,但你也可以使用DoubleSummaryStatistics:您可以在其他以後創建這個類的一個實例,然後讓它accept一個值,最後get the average而無需進行手動計算 - 順便說一句,您可以免費計算最小值和最大值。

private final DoubleSummaryStatistics stats = new DoubleSummaryStatistics(); 

public void onLocationChanged(Location location) 
{ 
    ... 
    float speed = ...; 

    stats.accept(speed); 
} 

void printSummary() 
{ 
    double average = stats.getAverage(); 
    double min = stats.getMin(); 
    double max = stats.getMax(); 
    ... 
} 

編輯:

如果你不使用Java 8的是,你可以做

private final List<Float> speeds = new ArrayList<Float>(); 

public void onLocationChanged(Location location) 
{ 
    ... 
    float speed = ...; 

    speeds.add(speed); 
} 

private float computeAverage(List<Float> values) 
{ 
    float sum = 0; 
    for (Float v : values) 
    { 
     sum += v; 
    } 
    return sum/values.size(); 
} 

void printSummary() 
{ 
    double average = computeAverage(speeds); 
    ... 
} 

(類似於@AndrewTobilko最初提出的)

+0

初學者,我應該創建一個DoubleSummaryStatistics類嗎?並在DoubleSummaryStatictics中創建一個方法accept? –

+0

@SuhailParvez這個類也是Java 8的一部分。如果你還沒有使用它,你可以使用最初由Andrew Tobilko提出的方法(他現在刪除了它 - 所以我在我的答案中添加了一個簡短描述) – Marco13

+0

你是我今日的英雄:P。太感謝了 :) –