Beginners Programs :

Java Distance Traveled By Vehicle Program | 4 Ways

Java code distance traveled by vehicle. the following java program has been written in multiple ways along with detailed explanation. If you have any queries for this java code for total distance traveled in Java just leave a comment here.

Distance traveled is equal to – Velocity*time taken to travel. To rephrase it –

Distance = Velocity*time taken to travel

Java distance traveled

Solved Examples

Question 1: A truck travels at a velocity of 20 miles per hour on a highway. Calculate the total amount of time taken by the truck to travel a distance of 100 miles?

Answer:

We know already that;

Velocity = 20 miles per hour

Displacement or d = 100 miles

displacement d = vt

The time taken is found out by

t = d/v

= 100/20

t = 5 hours

This is just to give you an idea about how it works in physics on layman’s terms. No that we have learnt how to do it in physics, here’s how to do it in Java.

 

Distance Traveled In Java Program

 

Before directly jumping into the solutions, it is advisable to follow a certain steps to avoid confusion at a later stage.

Firstly, we need to clearly understand the problem statement and also see if any specific constraints have been given in the problem statement.

Then we should figure out the inputs required for the solution along with our expected output. After deciding all this only, we arrive at the solution.

In this, our problem statement is to find the distance. To do this, our required inputs as speed and time.

As directly given in the problem statement our output is the final distance.

To get our inputs, we make use of the Scanner class which allows us to read inputs of any primitive datatype at runtime.

Our required inputs- speed and time, are both of double datatype. We take the speed in kmph and time in hours. To read at runtime, we first create an object to invoke the Scanner Class methods. This is done as follows:

After collecting our inputs, we now have to write the logic to calculate the distance. The formula used to calculate the distance is:

distance = speed * time.

Using this formula, we will get our desired output the distance in kilometres and if we want to convert it into metres we can just multiply it with thousand.

This value can then be printed in the output console screen by making use of System.out.println() function for printing in new line as follows:

Java Program:

Output: