In: Computer Science
Write a java program called ImperialMetric that displays a
conversion table for feet
and inches to metres. The program should ask the user to enter the
range of values that
the table will hold.
Here is an example of what should be output when the program
runs:
Enter the minimum number of feet (not less than 0):
5
Enter the maximum number of feet (not more than 30):
9
| | | | | | |
0" 1.524 1.829 2.134 2.438 2.743 |
1" 1.549 1.854 2.159 2.464 2.769 |
2" 1.575 1.880 2.184 2.489 2.794 |
3" 1.600 1.905 2.210 2.515 2.819 |
4" 1.626 1.930 2.235 2.540 2.845 |
5" 1.651 1.956 2.261 2.565 2.870 |
6" 1.676 1.981 2.286 2.591 2.896 |
7" 1.702 2.007 2.311 2.616 2.921 |
8" 1.727 2.032 2.337 2.642 2.946 |
9" 1.753 2.057 2.362 2.667 2.972 |
10" 1.778 2.083 2.388 2.692 2.997 |
11" 1.803 2.108 2.413 2.718 3.023 |
5' 6' 7' 8' 9' |
The sample solution used to generate the above example and the
automarker scripts
uses System.out.printf() with a format string of "%6.3f" to print
the metric values.
We recommend the following formula:
double metres = (feet*12+inches)*0.0254;
Solution: The required java code has been provided below, along with the output. Comments have been placed to depict the functionality.
main() has been implemented to complete the test.
import java.util.*;
public class PrintfTest
{
public static void main (String arg[])
{
//declare variables
int minfeet, maxfeet;
double metres;
//Scanner to ask user input
Scanner reader = new Scanner(System.in);
System.out.println("Enter the minimum number of feet(not less than 0)");
minfeet = reader.nextInt();
System.out.println("Enter the maximum number of feet(not more than 30)");
maxfeet = reader.nextInt();
//print the inches
System.out.printf("| ");
for (int i =0;i<12;i++)
{
System.out.printf(i+"'' ");
}
//print the minimum feet
System.out.printf(minfeet+"'"+"\n");
//Nested loop to calculate the metres and display
for (int j=minfeet;j<=maxfeet;j++)
{
System.out.printf("|");
for (int i=0;i<12;i++)
{
metres = ((j*12)+i) * 0.0254;
//Use formatted output
System.out.printf("%6.3f",metres);
}
if (j+1 < (maxfeet + 1))
{
System.out.printf(" "+(j+1)+"'"+"\n");
}
if (j+1 == maxfeet + 1)
{System.out.println("");}
}
}
}
Output:
Enter the minimum number of
feet(not less than 0)
5
Enter the maximum number of feet(not more than 30)
9
| 0''
1''
2''
3''
4''
5''
6''
7''
8'' 9''
10''
11'' 5'
| 1.524 1.549 1.575 1.600 1.626 1.651 1.676 1.702 1.727 1.753 1.778
1.803 6'
| 1.829 1.854 1.880 1.905 1.930 1.956 1.981 2.007 2.032 2.057 2.083
2.108 7'
| 2.134 2.159 2.184 2.210 2.235 2.261 2.286 2.311 2.337 2.362 2.388
2.413 8'
| 2.438 2.464 2.489 2.515 2.540 2.565 2.591 2.616 2.642 2.667 2.692
2.718 9'
| 2.743 2.769 2.794 2.819 2.845 2.870 2.896 2.921 2.946 2.972 2.997
3.023