cs175:loops_lab_-_temperature_conversion_tables
TempConvert - Temperature conversion tables
- Topics: Loops, using the counter variable
Write TempConvert.java
to output two temperature conversion tables.
- The first table that is output will show temperatures in the range 0 - 212 degrees Fahrenheit and the equivalent temperatures in Celsius.
- Increase Fahrenheit values in increments of two, i.e., 0, 2, 4, 6, …, 212
- Use a for loop.
- Use a for loop counter variable tempF (instead of i) to represent temperature in Fahrenheit.
- tempF will be used in the loop to calculate tempC, the equivalent Celsius temperature.
- The second table that is output will show temperatures in the range 0 - 100 degrees Celsius and the equivalent temperatures in Fahrenheit.
- Increase Celsius values in increments of two, i.e., 0, 2, 4, 6, …, 100
- Use a second for loop.
- The for loop counter variable used here will be called tempC to represent temperature in Celsius.
- tempC will be used in the loop to calculate tempF, the equivalent Fahrenheit temperature.
- Two formulas will be needed:
- Fahrenheit to Celsius: (°F - 32) / 1.8 = °C
- Celsius to Fahrenheit: °C × 1.8 + 32 = °F
The code:
// TempConvert.java // F-to-C and C-to-F conversion tables; // Uses two for loops public class TempConvert { public static void main(String[] args) { // F-to-C table: // Print table headings. // The \t (tab) characters help to set consistent columns // in the output. System.out.println("Fahrenheit" + "\t\t\t" + "Celsius"); // Print table values using a for loop. for ( int tempF = 0; tempF <= 212; tempF=tempF+2 ) { double tempC = (tempF - 32) / 1.8; System.out.println(tempF + "\t\t\t\t" + tempC); } // end for // Want an extra line between the tables System.out.println(); // C-to-F table: // Print table headings. System.out.println("Celsius" + "\t\t\t\t" + "Fahrenheit"); // Print table values using a for loop. for ( int tempC = 0; tempC <= 100; tempC=tempC+2 ) { double tempF = (tempC * 1.8) + 32; System.out.println(tempC + "\t\t\t\t" + tempF); } // end for } // end main } // end class
cs175/loops_lab_-_temperature_conversion_tables.txt · Last modified: 2015/12/03 21:17 by jchung