In: Computer Science
this is my assignment for intro to java tha i could not figure out, my system just crashed wit a lot of errors. thank for your help
Create a new Java class inside your project folder.
The name of the class should be:
TempConverter
Note that this means you should have the following line at the top
of your program:
public class TempConverter
Write a program that allows the user to convert a temperature given in degrees Celsius or Fahrenheit to the opposite value.
Begin by getting a temperature from the user. After the temperature, ask the user to enter "C" or "c" for Celsius or "F" or "f" for Fahrenheit. If the user enters anything other than "C" or "F", then display an error message telling the user to only enter "C" or "F".
Once you have a temperature and the unit, then convert the temperature to the opposite unit and display the result. The answer should be displayed with only one decimal place.
The formula to convert a Celsius temperature to Fahrenheit
is:
Degrees_F = (9(Degrees_C)/5) + 32)
The formula to convert a Fahrenheit temperature to Celsius
is:
Degrees_C = 5(Degrees_F− 32)/9
The following is an example of what your MIGHT see on the screen when your program runs. The exact output depends on what values that the user types in while the program runs. The user's values are shown below in italics:
Enter a temperature: 98.6
Enter (C)elsius or (F)ahrenheit: F
The equivalent temperature in Celsius is: 37.0
Here is another example run of the program:
Enter a temperature: 23.9
Enter (C)elsius or (F)ahrenheit: f
The equivalent temperature in Celsius is: -4.5
Here is another example run of the program:
Enter a temperature: 100
Enter (C)elsius or (F)ahrenheit: C
The equivalent temperature in Fahrenheit is: 212.0
Here is another example run of the program:
Enter a temperature: 49
Enter (C)elsius or (F)ahrenheit: M
Error: Enter only "C" or "F".
Program :
import java.util.Scanner;
public class TempConverter
{
public static void main(String args[])
{
char ch; // variable declaration
double temp,c,f;
System.out.print("Enter a temperature : ");
Scanner sc = new Scanner(System.in);
temp = sc.nextDouble(); // Accept temparature
System.out.println("Enter (C)elsius or (F)ahrenheit: F");
System.out.print("Enter Choice :");
ch = sc.next().charAt(0); // Accept choice
if(ch=='f'||ch=='F')
{
c = ((temp - 32) * 5) / 9; // convert temparature in Celsius
System.out.println("The equivalent temperature in Celsius is:" +
c);
}
if(ch=='c'||ch=='C')
{
f = (9 * temp / 5) + 32; // convert temparature in fahrenheit
System.out.println("The equivalent temperature in Fahrenheit is:"
+f);
}
System.out.println("Enter only C or F.");
}
}
Output :