Question 3(7 points) write a Java program that asks the user to enter the curren
ID: 3910197 • Letter: Q
Question
Question 3(7 points) write a Java program that asks the user to enter the current temperature from the keyboard. If the entered temperature is in Fahrenheit, then the program should calculate and display the Celsius equivalent to it. If the entered temperature is in Celsius, then your program should calculate and display the Fahrenheit equivalent to it. Your program should have at least two methods, method 1 is called convertToCelsius0, and the other method is called convertToFahrenheit). To convert from Fahrenheit to Celsius, you can use the following equation: celsius 5.0/9.0*(fahrenheit - 32) To convert from Celsius to Fahrenheit, you can use the following equation: Fahrenheit-9.0/5.0 celsius +32Explanation / Answer
ScreenShot
--------------------------------------------------------------
Program
//Header file for I/O
import java.text.DecimalFormat;
import java.util.*;
//Converter class
public class Converter {
//Convert Fahrenheit to Celcius function
public static double convertToCelcius(double val) {
return ((5.0/9.0)*(val-32));
}
//Convert Celcius to Fahrenheit function
public static double convertToFahreheit(double val) {
return ((9.0/5.0)*val)+32;
}
//Main method
public static void main(String[] args) {
//Scanner to read input
Scanner sc=new Scanner(System.in);
//For input
double in=0;
//Formatter
DecimalFormat df=new DecimalFormat("#.##");
//Prompt user to enter temperature
System.out.println("Please enter temperature(if fahrenheit put 'k' at the end Otherwise 'c':");
String input=sc.nextLine();
//find the last character to detect conversion
char ch=input.charAt((input.length())-1);
//convert according to the last character
if(ch=='f') {
in=Double.parseDouble(input.replace('f',' '));
System.out.println(input+"="+df.format(convertToCelcius(in))+"C");
}
else if(ch=='F') {
in=Double.parseDouble(input.replace('F',' '));
System.out.println(input+"="+df.format(convertToCelcius(in))+"C");
}
else if(ch=='c') {
in=Double.parseDouble(input.replace('c',' '));
System.out.println(input+"="+df.format(convertToFahreheit(in))+"F");
}
else if(ch=='C') {
in=Double.parseDouble(input.replace('C',' '));
System.out.println(input+"="+df.format(convertToFahreheit(in))+"F");
}
else {
System.out.println("Entered input is wrong");
}
}
}
-----------------------------------------------
Output
Please enter temperature(if fahrenheit put 'k' at the end Otherwise 'c':
270f
270f=132.22C
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.