Reference no: EM13166134
Distance Travelled Java how to go about modifying my code to complete this hw question.
Here is the question: Distance Traveled Modification
The distance a vehicle travels can be calculated as follows:
distance=Speed * time
Write a method named distance that accepts a vehicle's speed and rime as arguments, and
returns the distance the vehicle has traveled. Modify the "Distance Traveled" program you
wrote in Chapter 4.
My code for that problem was :
import javax.swing.JOptionPane; // Joption class
public class PROB4_CHAL2
{
public static void main(String[] args)
{
int distance;
int speed;
int time;
String input;
input = JOptionPane.showInputDialog("What is the speed " +
"of the vehicle in miles-per-hour?");
speed = Integer.parseInt(input);
while (speed < 0)
{
input = JOptionPane.showInputDialog("What is the speed " +
"of the vehicle in MPH? " +
"Please enter a POSITIVE number");
speed = Integer.parseInt(input);
}
input = JOptionPane.showInputDialog("How many hours " +
"has the vehicle travelled?");
time = Integer.parseInt(input);
while (time < 1)
{
input = JOptionPane.showInputDialog("How many hours " +
"has the vehicle travelled? " +
"Please enter a value that is no less than 1");
time = Integer.parseInt(input);
}
distance = speed * time;
String out = "Hour Distance Travelled\n\nTotal Hours: " + time + "\nTotal Distance: " + distance + "\n\n";
for(int i=1; i<=time; i++)
{
out+= "Hour " + i + ": " + (speed*i) + " miles travelled\n";
}
JOptionPane.showMessageDialog(null, out);
}
}