C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Calculate Speed = Distance / Time + Unit Handling

Speed Formula

        Java Programs

Supported Units

  • Distance: Kilometers (km)
  • Time: Hours (h)
  • Speed Output: km/h

 

import java.util.Scanner;

 

public class SpeedCalculator {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter distance traveled (in kilometers): ");

        double distance = sc.nextDouble();

 

        System.out.print("Enter time taken (in hours): ");

        double time = sc.nextDouble();

 

        System.out.println("\n------ Speed Calculation ------");

 

        if (time <= 0) {

            System.out.println("Time must be greater than zero.");

        } else {

            double speed = distance / time;

            System.out.printf("Distance : %.2f km%n", distance);

            System.out.printf("Time     : %.2f hours%n", time);

            System.out.printf("Speed    : %.2f km/h%n", speed);

        }

 

        sc.close();

    }

}

Output

OUTPUT 1:

INPUT : 
Enter distance traveled (in kilometers): 150
Enter time taken (in hours): 3

OUTPUT : 
------ Speed Calculation ------
Distance : 150.00 km
Time     : 3.00 hours
Speed    : 50.00 km/h

OUTPUT 2: (Invalid Case)

INPUT : 
Enter distance traveled (in kilometers): 100
Enter time taken (in hours): 0

OUTPUT : 
------ Speed Calculation ------
Time must be greater than zero.

Explanation

1. Input Distance and Time

double distance = sc.nextDouble();

double time = sc.nextDouble();

  • Reads distance in kilometers and time in hours.

2. Validation of Time

if (time <= 0)

  • Prevents division by zero or invalid time values.

3. Speed Calculation

       Java Programs

double speed = distance / time;

4. Unit Handling

  • Input units are km and hours.
  • Output speed is automatically km/h.

5. Formatted Output

System.out.printf("%.2f", speed);

  • Displays speed with 2 decimal places.