Float, speed units Learn programming Java

Lesson:

Basic Data Types


Exercise:

Float, speed units


Objetive:

Create a java program to ask the user for a distance (in meters) and the time taken (as three numbers: hours, minutes, seconds), and display the speed, in meters per second, kilometers per hour, and miles per hour (hint: 1 mile = 1609 meters).


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		float distance;
		float hour, min, sec;

		float timeSec;
		float mps;
		float kph, mph;

		System.out.print("Enter distance(meters): ");
		distance = Float.parseFloat(new Scanner(System.in).nextLine());

		System.out.print("Enter timeSec(hour): ");
		hour = Float.parseFloat(new Scanner(System.in).nextLine());

		System.out.print("Enter timeSec(minutes): ");
		min = Float.parseFloat(new Scanner(System.in).nextLine());

		System.out.print("Enter timeSec(seconds): ");
		sec = Float.parseFloat(new Scanner(System.in).nextLine());

		timeSec = (hour * 3600) + (min * 60) + sec;
		mps = distance / timeSec;
		kph = (distance / 1000.0f) / (timeSec / 3600.0f);
		mph = kph / 1.609f;

		System.out.printf("Your speed in meters/sec is %1$s" + "\r\n", mps);
		System.out.printf("Your speed in km/h is %1$s" + "\r\n", kph);
		System.out.printf("Your speed in miles/h is %1$s" + "\r\n", mph);
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.