import java.util.Scanner;
import java.io.*;
/**
DistanceFile
CS 111A Programming Lab 7 solution
by Tony Gaddis for Starting Out with Java
modified by Craig Persiko
*/
public class DistanceFile
{
/* input a number from the user, using prompt as an inline prompt,
ensuring the number is >= num. The name of this data is name. */
private static double getNumber(String prompt, int min, String name)
{
Scanner keyboard = new Scanner(System.in);
double num;
System.out.print(prompt);
num = keyboard.nextDouble();
// Validate the speed.
while (num < min)
{
System.out.print("Enter " + min + " or greater for " + name + ": ");
num = keyboard.nextDouble();
}
return num;
}
public static void main(String[] args) throws IOException
{
double speed; // The vehicle's speed
int maxHours, // Max number of hours traveled
period; // To count time periods
// Get the speed.
speed = getNumber("Enter the vehicle's speed: ", 0, "speed");
// Get the number of hours.
maxHours = (int)getNumber("Enter the number of hours the " +
"vehicle was in motion: ", 1, "hours");
// Create the objects necessary to perform file output.
FileWriter fw = new FileWriter("DistanceReport.txt");
PrintWriter outFile = new PrintWriter(fw);
// Write the table header.
outFile.printf ("Hour Distance Traveled\n");
outFile.println("----------------------------------");
// Write the table of distances.
period = 1;
while (period <= maxHours)
{
// Display the distance for this period.
outFile.printf("%3d %,24.1f\n",period, period * speed);
// Increment period.
period++;
}
// Close the file.
outFile.close();
System.out.println("Report written to DistanceReport.txt.");
}
}
/* Sample Output:
-bash-3.2$ java DistanceFile
Enter the vehicle's speed: 120
Enter the number of hours the vehicle was in motion: 11
Report written to DistanceReport.txt.
-bash-3.2$ cat DistanceReport.txt
Hour Distance Traveled
----------------------------------
1 120.0
2 240.0
3 360.0
4 480.0
5 600.0
6 720.0
7 840.0
8 960.0
9 1,080.0
10 1,200.0
11 1,320.0
-bash-3.2$ java DistanceFile
Enter the vehicle's speed: -2
Enter 0 or greater for speed: 3.25
Enter the number of hours the vehicle was in motion: 0
Enter 1 or greater for hours: 4
Report written to DistanceReport.txt.
-bash-3.2$ cat DistanceReport.txt
Hour Distance Traveled
----------------------------------
1 3.3
2 6.5
3 9.8
4 13.0
-bash-3.2$
*/
syntax highlighted by Code2HTML, v. 0.9