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

Distance Traveled and distance file both are java thanks a alot Programming Cha

ID: 3822546 • Letter: D

Question


Distance Traveled
and
distance file both are java
thanks a alot

Programming Cha enges 2. Distance Traveled 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 the speed of a vehicle (in miles r and the number of hours it has traveled. It should use a loop t display the vehicle has distance a traveled for hour of a time period specified by the user. For example, a vehicle is traveling at 40 mph for a three-hour time period, it should display a report similar to the one that follows: Distance Traveled 40 80 120 gative number for speed and do not accept any Input Validation: Do not accept a ne less than 1 for time traveled. 3. Distance File Challenge 2 (Distance so it Modify the program you wrote for Programming Travel text writes the report to a file instead of the screen. Open the file in Notepad or another editor to confirm the output. on 1000 in

Explanation / Answer

2.

import java.util.Scanner;


public class DistanceTravelled {

public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
  
int speed;
while(true)
{
System.out.print("Enter vehicle speed (in miles-per-hour): ");
speed = sc.nextInt();
if (speed < 0)
{
System.out.println("Enter a positive value for speed. Try again!");
}
else
{
break;
}
}
  
int time;
while(true)
{
System.out.print("Enter time in hours: ");
time = sc.nextInt();
if (time < 1)
{
System.out.println("Enter a value greater than equal to 1 for time. Try again!");
}
else
{
break;
}
}
  
  
System.out.println("Hour Distance Travelled");
System.out.println("--------------------------");
for(int i = 1; i <= time; i++)
{
System.out.println(i + " " + i*speed);
}
sc.close();
}
}

3.

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


public class DistanceTravelled {

public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
  
int speed;
while(true)
{
System.out.print("Enter vehicle speed (in miles-per-hour): ");
speed = sc.nextInt();
if (speed < 0)
{
System.out.println("Enter a positive value for speed. Try again!");
}
else
{
break;
}
}
  
int time;
while(true)
{
System.out.print("Enter time in hours: ");
time = sc.nextInt();
if (time < 1)
{
System.out.println("Enter a value greater than equal to 1 for time. Try again!");
}
else
{
break;
}
}
  
FileWriter fw = new FileWriter("distance_travelled.txt");
fw.write("Hour Distance Travelled ");
fw.write("-------------------------- ");
for(int i = 1; i <= time; i++)
{
fw.write(i + " " + i*speed + " ");
}
fw.close();
sc.close();
}
}