My code compiles, but when running it, it continues to infinity. How do I change that?
Here is the problem:
The distance a vehicle travels can be calculated as follows:
Distance = Speed * Time
For example, if a train travels 40 miles-per-hour for three hours, the distance traveled is 120 miles. Write a program that asks for the speed of a vehicle (in mph) and the number of hours it has traveled. It should use a loop to display the distance a vehicle has traveled for each hour of a time period specified by the user. For example, if a vehicle is traveling at 40 mph for a three-hour time period, it should display a report similar to the one that follows:
Hour Distance Traveled
--------------------------------------------
1 40
2 80
3 120
Input Validation: Do not accept a negative number for speed and do not accept any value less than 1 for time traveled.
Here is my code:
import java.util.Scanner; public class DistanceTraveled { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int vehicleSpeed = 0, hoursTraveled = 0, hours = 1; System.out.print("Enter the vehicle speed: "); vehicleSpeed = keyboard.nextInt(); while (vehicleSpeed < 0) { System.out.print("Enter the vehicle speed: "); vehicleSpeed = keyboard.nextInt(); } System.out.print("Enter the amount of hours traveled: "); hoursTraveled = keyboard.nextInt(); while (hoursTraveled < 1) { System.out.print("Enter the amount of hours taveled (MPH): "); hoursTraveled = keyboard.nextInt(); } System.out.println("Hours" + " Distance Traveled"); System.out.println("--------------------------------------"); while (hours >= 1) { System.out.println(" " + hours + " " + hours * vehicleSpeed + "MPH"); hours++; hoursTraveled--; } } }