Matthijs - 5 months ago 11

Java Question

On my android google map application I'm trying to calculate the average speed by taking the time (in milliseconds) and distance (in meters) and performing the next calculation on it:

`private double avgSpeed = 0;`

public void calcAvgSpeed(double distance, long time) {

distance = distance / 1000; //1000 = km

time = time / 3600000; // 1000 = sec, 60000 = min, 3600000 = hrs

avgSpeed = (double) (distance / time);

}

to make sure it works i ran it with

`calcAvgSpeed(300, 30000);`

Does anybody see if my method is wrong or why I get this weird answer?

Answer

You are indeeed dividing by zero.

```
time = time / 3600000;
```

performs an integer division since `time`

is of type `long`

.

To fix this use something like

```
avgSpeed = distance * 3600000 / time;
```