Hi all. I'm having trouble with this simple Java program. When I compile it, numerous errors would happen. I put in let's say 50 miles for the speed of the car and 2 hours for the traveling hours. I run it and it you see this:
Hours Distance Traveled
---------------------------------
2 100
2 100
It doesn't display the 1 hour which it's supposed to be 50 miles traveled.
Also, I try to test the while loops with negative or 0 inputs, and I get a repeat of the output which looks like this:
Enter the speed of the vehicle in miles-per-hour: -1
Your speed must be greater than zero. Please re-enter.
Your speed must be greater than zero. Please re-enter.
Enter the number of hours that you have traveled: 0
Your hours must be at least 1 or more. Please re-enter.
Your hours must be at least 1 or more. Please re-enter.
Hours Distance Traveled
---------------------------------
2 2
2 2
I have been stuck finding the solution for a while, and I'd like some help, please. Thank you. Here's my code:
// This program asks the user for the speed of a vehicle (in miles-per-hour) and
// the number of hours it has traveled.
// Chapter 4 #2 Programming Challenge.
// Programmed by X.
// 2/27/2012.
import java.util.Scanner;
public class DistanceTraveled
{
public static void main(String args[])
{
String input; // hold user's input
int MPH; // miles per hour
int time; // time in hours traveled
int i; // placeholder for starting point of time
int distance; // distance
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the number of miles driven from user.
System.out.print("Enter the speed of the vehicle in miles-per-hour: ");
MPH = keyboard.nextInt(); // converts the string into a numeric value.
while (MPH <= 0)
{
System.out.print("Your speed must be greater than zero. Please re-enter.\n ");
MPH++;
}
// Get the hours traveled from the user.
System.out.print("Enter the number of hours that you have traveled: ");
time = keyboard.nextInt(); // converts the string into a numeric value.
while (time <= 1)
{
System.out.print("Your hours must be at least 1 or more. Please re-enter.\n ");
time++;
}
// Formula for finding the distance.
distance = MPH*time;
// Output the distance that the vehicle has traveled for each hour.
System.out.println("Hours Distance Traveled");
System.out.println("---------------------------------");
for (i = 1; i <= time; i++)
{
System.out.println(time + "\t\t" + (distance));
}
}
}