## Friday, 19 August 2016

### Chapter 6 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

6.8 (Conversions between Celsius and Fahrenheit) Write a class that contains the fol- lowing two methods:

/** Convert from Celsius to Fahrenheit */
public static double celsiusToFahrenheit(double celsius)

/** Convert from Fahrenheit to Celsius */
public static double fahrenheitToCelsius(double fahrenheit)

The formula for the conversion is:

fahrenheit = (9.0 / 5) * celsius + 32
celsius = (5.0 / 9) * (fahrenheit – 32)

Write a test program that invokes these methods to display the following tables:

Celsius Fahrenheit | Fahrenheit Celsius
40.0 104.0 | 120.0 48.89
39.0 102.2 | 110.0 43.33
...
32.0 89.6 | 40.0 4.44
31.0 87.8 | 30.0 -1.11

public class ProgrammingExercise6_8 {

public static void main(String[] args) {

System.out.printf("%-15s%-15s|    %-15s%-15s\n","Celsius","Fahrenheit","Fahrenheit","Celsius");
System.out.println( String.format("%62s"," ").replace(' ', '-') );

for (int c = 40, f = 120  ; c >=31; c--, f-=10) {

System.out.printf("%-15.1f%-15.1f|    %-15.1f%-15.2f\n",(float)c,celsiusToFahrenheit(c),(float)f, fahrenheitToCelsius(f));

}

}

/** Convert from Celsius to Fahrenheit */
public static double celsiusToFahrenheit(double celsius) {
return (9.0 / 5) * celsius + 32;
}

/** Convert from Fahrenheit to Celsius */
public static double fahrenheitToCelsius(double fahrenheit) {
return (5.0 / 9) * (fahrenheit - 32);
}

}