My code asks the user for the type of conversion, the degrees and spits the result back. It will prompt the user to ask for the type of conversion again if it's invalid. It will also prompt the user to see if he wants to quit or rerun the program again.
I was wondering if there is a more efficient way of doing this. I feel like I have a lot of redundant code on here.
public class Problem4 {
public static double celsiusToFahrenheit(double degree_C)
{
double fahrenheitResult = (9*(degree_C) / 5) + 32;
return fahrenheitResult;
}
public static double fahrenheitToCelsius(double degree_F)
{
double celsiusResult = 5*(degree_F - 32)/9;
return celsiusResult;
}
public static void init(){
Scanner scan = new Scanner(System.in);
double result;
char cont= 'y';
char type;
while (cont!='q' && cont!='Q')
{
System.out.println("Please enter the degree:");
double degree = scan.nextDouble();
System.out.println("Now enter the type of conversion (For Celsius, type 'C'. For Fahrenheit, type 'F')");
type = scan.next().charAt(0);
if(type!='c' && type!='C' && type!='f' && type!='F')
{
System.out.println("Error! You've entered an invalid conversion type!");
System.out.println("Please enter a valid selection (Type C for celsius and F for fahrenheit");
type = scan.next().charAt(0);
}
if (type == 'F' || type =='f')
{
result = fahrenheitToCelsius(degree);
System.out.println("The conversion of "+ degree+"°F "+ "to Celsius is: " + result + "°C");
}
if (type == 'C' || type =='c')
{
result = celsiusToFahrenheit(degree);
System.out.println("The conversion of "+ degree+"°C "+ "to Fahrenheit is: " + result + "°F");
}
System.out.println("Would you like to quit? Type 'q' to quit or type any other letter to continue:");
cont = scan.next().charAt(0);
}
scan.close();
}
public static void main(String[] args)
{
init();
}
}