Questions: Temperature Conversions
Implement the following integer methods:a) Method celsius returns the Celsius equivalent of a Fahrenheit temperature, using the calculation
celsius = 5.0 / 9.0 * ( fahrenheit - 32 );
b) Method fahrenheit returns the Fahrenheit equivalent of a Celsius temperature, using the calculation
fahrenheit = 9.0 / 5.0 * celsius + 32;
c) Use the methods from parts (a) and (b) to write an application that enables the user either to enter a Fahrenheit temperature and display the Celsius equivalent or to enter a Celsius temperature and display the Fahrenheit equivalent.
Solutions: Temperature Conversions
// Program converts Fahrenheit to Celsius. and vice versa.import java.util.Scanner;
public class TemperatureConversion
{
public static void main (String [] args)
{
Scanner input = new Scanner( System.in );
int choice; // the user's choice in the menu
do
{
// print the menu
System.out.println( "1 Fahrenheit to Celsius" );
System.out.println( "2 Celsius to Fahrenheit" );
System.out.println( "3 Exit" );
System.out.print( "Choice: " );
choice = input.nextInt();
if ( choice != 3 )
{
System.out.print( "Enter temperature: " );
int oldTemperature = input.nextInt();
// convert the temperature appropriately
switch ( choice )
{
case 1:
System.out.printf( "%d Fahrenheit is %d Celsius\n",
oldTemperature, celsius( oldTemperature ) );
break;
case 2:
System.out.printf( "%d Celsius is %d Fahrenheit\n",
oldTemperature, fahrenheit( oldTemperature ) );
break;
default:
System.out.println("Wrong Choice, try again!");
} // end switch
} // end if
}// end do
while ( choice != 3 );
} // end method main
// return Celsius equivalent of Fahrenheit temperature
public static int celsius( int fahrenheitTemperature )
{
return ( (int) ( 5.0 / 9.0 * ( fahrenheitTemperature - 32 ) ) );
} // end method celsius
// return Fahrenheit equivalent of Celsius temperature
public static int fahrenheit( int celsiusTemperature )
{
return ( (int) ( 9.0 / 5.0 * celsiusTemperature + 32 ) );
} // end method fahrenheit
} // end class TemperatureConversion