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
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();
}
}