asked 127k views
1 vote
The distance a vehicle travels can be calculated as follows:

Distance = Speed * Time
Design a Java program that asks a user for the speed of a vehicle in miles per hour and how many hours it has travelled (Assume the two values are integers). Your program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. (For example, entering 50 mph and 4 hours should produce output like: Hour 1: 50 miles, Hour 2: 100 miles, Hour 3: 150 miles, Hour 4: 200 miles. )

1 Answer

5 votes

Answer:

Here's an example Java program that asks the user for the speed of a vehicle in miles per hour and the number of hours it has traveled, then uses a loop to display the distance the vehicle has traveled for each hour of that time period:

import java.util.Scanner;

public class DistanceCalculator {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Ask the user for the speed and time

System.out.print("Enter the speed of the vehicle (in mph): ");

int speed = input.nextInt();

System.out.print("Enter the number of hours it has traveled: ");

int time = input.nextInt();

// Calculate and display the distance for each hour

for (int hour = 1; hour <= time; hour++) {

int distance = speed * hour;

System.out.printf("Hour %d: %d miles\\", hour, distance);

}

}

}

In this program, we first create a new Scanner object to read input from the console. We then prompt the user to enter the speed of the vehicle and the number of hours it has traveled using the nextInt() method of the Scanner object.

We then use a for loop to iterate over each hour of the time period. For each hour, we calculate the distance the vehicle has traveled using the formula distance = speed * hour, where speed is the user-entered speed and hour is the current hour of the loop.

Finally, we use the printf() method to display the distance for each hour in the format "Hour x: y miles", where x is the current hour and y is the distance traveled. The format specifier %d tells printf() to display the integer argument in decimal format.

answered
User Promise
by
7.8k points

No related questions found