KnowledgeBoat Logo

Computer Applications

The relative velocity of two trains travelling in opposite directions is calculated by adding their velocities. In case, the trains are travelling in the same direction, the relative velocity is the difference between their velocities. Write a program to input the velocities and length of the trains. Write a menu driven program to calculate the relative velocities and the time taken to cross each other.

Java

Java Conditional Stmts

74 Likes

Answer

import java.util.Scanner;

public class KboatTrain
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        
        System.out.println("1. Trains travelling in same direction");
        System.out.println("2. Trains travelling in opposite direction");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        
        System.out.print("Enter first train velocity: ");
        double speed1 = in.nextDouble();
        System.out.print("Enter first train length: ");
        double len1 = in.nextDouble();
        
        System.out.print("Enter second train velocity: ");
        double speed2 = in.nextDouble();
        System.out.print("Enter second train length: ");
        double len2 = in.nextDouble();
        
        double rSpeed = 0.0;
        
        switch(choice) {
            case 1:
                rSpeed = Math.abs(speed1 - speed2);
                break;
                
            case 2:
                rSpeed = speed1 + speed2;
                break;
                
            default:
                System.out.println("Wrong choice! Please select from 1 or 2.");
        }
        
        double time = (len1 + len2) / rSpeed;
        
        System.out.println("Relative Velocity = " + rSpeed);
        System.out.println("Time taken to cross = " + time);
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of The relative velocity of two trains travelling in opposite directions is calculated by adding their velocities. In case, the trains are travelling in the same direction, the relative velocity is the difference between their velocities. Write a program to input the velocities and length of the trains. Write a menu driven program to calculate the relative velocities and the time taken to cross each other.

Answered By

24 Likes


Related Questions