This is the first exercise in the series of Java Beginner’s Exercises.
In this exercise we will be finding the average speed of an object by using the distance and time only.
Problem
Flight AA 72 flying from Sydney to Los Angeles takes approximately 14 hours to travel 12,000 km. For our very first Java beginner’s exercise, write a Java program that will output the average speed of the plane in km/h.
Note
Before we dive into coding, let’s take a look how you can calculate the average speed of an object. We must use the “average speed = total distance/total time” formula to calculate the average speed of the plane.
Inputting these values and dividing them will give you the average speed of the plane.
For this probelm the total distance is 12,000 km and the total time is 14 hours.
Sample Solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int averageSpeed;
System.out.println("Input your total distance: ");
int totalDistance = scanner.nextInt();
System.out.println("Input your total time: ");
int totalTime = scanner.nextInt();
averageSpeed = totalDistance/totalTime;
System.out.println("The average speed of the plane is " + averageSpeed + " km/hr.");
}
}
Expected Output
If everything goes right, then the output should be 857 km/hr.
Conclusion
Well there you have it. The first exercise in the series of Java Beginner’s Exercise.
Make sure to play around with your code and explore different options. You can always input different values in the cases of total distance and total time.
Feel free to share this tutorial. Also comment below if you have any concerns or questions .