1
+ package com .codefortomorrow .intermediate .chapter11 .solutions ;
2
+
3
+ import java .util .Scanner ;
4
+
5
+ /*
6
+ Write a class that contains the following two methods:
7
+
8
+ Convert from Celsius to Fahrenheit
9
+ public static double celsiusToFahrenheit(double celsius)
10
+
11
+ Convert from Fahrenheit to Celsius
12
+ public static double fahrenheitToCelsius(double fahrenheit)
13
+
14
+ The formula for the conversion is:
15
+ fahrenheit = (9.0 / 5) * celsius + 32
16
+ celsius = (5.0 / 9) * (fahrenheit – 32)
17
+
18
+ Write a test program that asks the user for a temperature
19
+ in Fahrenheit and prints out the Celsius conversion. Then
20
+ ask the user for a temperature in Celsius and print out
21
+ the Fahrenheit conversion.
22
+
23
+ Adapted from Exercise 6.8, Introduction to Java Programming (Comprehensive),
24
+ 10th ed. by Y. Daniel Liang
25
+ */
26
+
27
+ public class Temperature {
28
+
29
+ public static void main (String [] args ) {
30
+ Scanner input = new Scanner (System .in );
31
+
32
+ // prompt user for temp in deg F
33
+ System .out .print ("Enter the temperature in degrees Fahrenheit: " );
34
+ double fahrenheit = input .nextDouble ();
35
+
36
+ // print that temp in deg C
37
+ System .out .println (fahrenheit + " deg F is " + fahrenheitToCelsius (fahrenheit ) + " deg C" );
38
+
39
+ // prompt user for temp in deg C
40
+ System .out .print ("Enter the temperature in degrees Celsius: " );
41
+ double celsius = input .nextDouble ();
42
+
43
+ // print that temp in deg F
44
+ System .out .println (celsius + " deg C is " + celsiusToFahrenheit (celsius ) + " deg F" );
45
+
46
+ input .close ();
47
+ }
48
+
49
+ /**
50
+ * Convert from Celsius to Fahrenheit
51
+ * @param celsius temperature in degrees Celsius
52
+ * @return temperature in degrees Fahrenheit
53
+ */
54
+ public static double celsiusToFahrenheit (double celsius ) {
55
+ return (9.0 / 5 ) * celsius + 32 ;
56
+ }
57
+
58
+ /**
59
+ * Convert from Fahrenheit to Celsius
60
+ * @param fahrenheit temperature in degrees Fahrenheit
61
+ * @return temperature in degrees Celsius
62
+ */
63
+ public static double fahrenheitToCelsius (double fahrenheit ) {
64
+ return (5.0 / 9 ) * (fahrenheit - 32 );
65
+ }
66
+ }
0 commit comments