Ticker

6/recent/ticker-posts

Header Ads Widget

Temperature conversion using switch statement

Temperature conversion using switch statement



Introduction
In this tutorial we will learn how to create a java program for temperature conversion from fahrenheit to Celsius using switch statement.


Let first understand how and what we will perform throughout coding.

Firstly, we create a variable to store temperature that would be e given by user and second the logic will provide to user, means convered temperature .

 We firstly put small menu for the user so that he can select what he want to perform whether he want to convert the Fahrenheit to Celsius or Celsius to Fahrenheit and we declare another variable to take a input from user and name the variable it as choice and this choice will be the input for the switch statement. 

Afterward we create three cases 1 and 2 for the Fahrenheit to Celsius and Celsius to Fahrenheit respectively and other as a default. In first case we allow user to convert Fahrenheit to Celsius in another celsius to fahrenheit using the formula shown below.

Formula to convert Fahrenheit to Celsius :-


countemp = (temp -32)/1.8 




Formula to convert Celsius to Fahrenheit:-


countemp = (1.8*temp) + 32 



Now let's start coding part.


Q) write a Java program for temperature conversion using switch statement.

Sol)



import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int choice;
double temp,countemp;
System.out.printf("Temperatur conversion menu (°C to F) \n");
System.out.printf("1. fahrenheit to Celsius " + "\n");
System.out.printf("2. Celsius to fahrenhiet " +"\n");
System.out.printf("enter your choice:" );
choice = in.nextInt();
switch(choice)
{
case  1:System.out.printf("\n" + "enter
temperature in Fahrenheit :");
temp =in.nextDouble();
countemp = (temp -32)/1.8 ;
System.out.printf(" the temperature in clesius is :" + countemp + "\n");
break;

case  2:System.out.printf("\n" + "enter temperature in centigrade :");
temp =in.nextDouble();
countemp = (1.8*temp) + 32 ;
System.out.printf(" the temperature in Fahrenheit is : " +countemp +"\n");
break;
default:System.out.printf("wrong! somethings went wrong");

break;
}
}
}





Output:

Temperatur conversion menu (°C to F)
1. fahrenheit to Celsius
2. Celsius to fahrenhiet
enter your choice:1

enter temperature in Fahrenheit :240
 the temperature in clesius is :115.55555555555556






Post a Comment

0 Comments