How to calculate time if we have the distance and speed (kilometers per hour) in Java

1 Answer

0 votes
import java.util.Scanner;

public class TravelTimeCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input distance and speed
        System.out.print("Enter distance (in km): ");
        double distance = Double.parseDouble(scanner.nextLine());

        System.out.print("Enter speed (in km/h): ");
        double speed = Double.parseDouble(scanner.nextLine());

        // Check to avoid division by zero
        if (speed <= 0) {
            System.out.println("Speed must be greater than zero.");
            return;
        }

        // Calculate time
        double tm = distance / speed;

        // Output result
        System.out.printf("Time required: %.2f hours%n", tm);

        // Optional: convert to hours and minutes
        int hours = (int) tm;
        int minutes = (int) ((tm - hours) * 60);

        System.out.printf("Which is approximately %d hours and %d minutes.%n", hours, minutes);

        scanner.close();
    }
}



/*
run:

Enter distance (in km): 30
Enter speed (in km/h): 90
Time required: 0.33 hours
Which is approximately 0 hours and 20 minutes.

*/

 



answered Dec 5, 2025 by avibootz

Related questions

...