Write a Java Program to accept the Distance travelled bya Car (d) and the time taken(t) by the Car to travel such distance. Calculate and display the Speed of the Car. [Speed=Distance/Time.]
Answers
Speed - Java
Speed is defined as the rate of change of position of an object in any direction. It's calculated as the distance travelled divided by the amount of time it took to travel that distance.
We'll be using the same formula to calculate the speed of the car.
We'll import package to take user inputs to accept the values of Distance travelled and time taken by the car. And we'll store them as double data type.
Then, we'll use the formula and display it.
Here's the program:
The Java Program
// Program to calculate the speed of the car
import java.util.Scanner; // Importing the scanner class for input
public class Speed // Declaring class name as "Speed"
{
// The Main method is required in every java program
public static void main(String[] args)
{
// Creating object of scanner class
Scanner sc = new Scanner(System.in);
// Taking user input to accept the value of distance by the car and it in double data type
System.out.print("Enter the value of distance travelled by the car: ");
double distance = sc.nextDouble();
// Taking user input to accept the value of distance by the car and it in double data type
System.out.print("Enter the value of time taken by the car: ");
double time_taken = sc.nextDouble();
// Closing scanner class after use
sc.close();
// Calculating the speed of the car
// Speed = Distance/Time taken
double speed = distance/time_taken;
// Displaying the result of the speed of the car
System.out.println("The speed of the car is: " + speed);
}
}
Sample run
Enter the value of distance travelled by the car: 50
Enter the value of time taken by the car: 5
The speed of the car is: 10.0