Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Distance Travelled Java Help. I am a bit confused on how to go about modifying m

ID: 3552708 • Letter: D

Question

Distance Travelled Java Help. I am a bit confused on 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 Total Hours: " + time + " Total Distance: " + distance + " ";

for(int i=1; i<=time; i++)

{

out+= "Hour " + i + ": " + (speed*i) + " miles travelled ";

}

JOptionPane.showMessageDialog(null, out);

}

}

Explanation / Answer

import java.util.*;

public class untitled
{

public static void main(String args[])

{int distance,speed,time,i;
Scanner in=new Scanner(System.in);
char cont='y';
while(cont=='y'||cont=='Y')
{
System.out.print("Enter the vehicles speed ");
speed=in.nextInt();
while(speed<0)
    {System.out.println("Negative speed isinvalid");
      System.out.print("Enter the vehiclesspeed ");
     speed=in.nextInt();
      }
System.out.print("Enter hours travelled ");
time=in.nextInt();
while(time<1)
    {System.out.println("hours must be at least1");
      System.out.print("Enter hours travelled");
     time=in.nextInt();
      }
System.out.println("Hour      DistanceTravelled");
System.out.println("----------------------------");
for(i=1;i<=time;i++)
  System.out.println(i+"            "+distance(speed,i));
System.out.print("again? answer Y: ");
cont=in.next().charAt(0);
}  

}
public static int distance(int speed,int time)
{returnspeed*time;              
}
}