Omar Sugule
Omar Sugule

Reputation: 17

How would you add another method in this program? Converting temperature

I am new to java and i read a few chapters. Just can't figure out how to use another method in this program that converts temps from F to C and vice versa Here is my code right now:

import java.io.*;
import javax.swing.JOptionPane;

public class Converter {
    public static void main(String[] args) throws Exception{


        String unit = JOptionPane.showInputDialog("Enter unit F or C: ");

        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String temp1 = JOptionPane.showInputDialog("Enter the Temperature: ");


        double temp = Double.valueOf(temp1).doubleValue();


         if((unit.equals("F"))||(unit.equals("f"))){
        double c= (temp - 32) / 1.8;
        JOptionPane.showMessageDialog(null,c+" Celsius");
        }

         else if((unit.equals("C"))||(unit.equals("c"))){
        double f=((9.0 / 5.0) * temp) + 32.0;
        JOptionPane.showMessageDialog(null,f+" Fahrenheit");

}
}
}

Upvotes: 0

Views: 1039

Answers (3)

Rahul Borkar
Rahul Borkar

Reputation: 2762

Here it is,

public class Converter {
public static void main(String[] args) throws Exception{


    String unit = JOptionPane.showInputDialog("Enter unit F or C: ");

    //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String temp1 = JOptionPane.showInputDialog("Enter the Temperature: ");


    double temp = Double.valueOf(temp1).doubleValue();
    double f = getTemprature(temp, unit);

    JOptionPane.showMessageDialog(null,f+" Fahrenheit");

}

    double getTemprature(double temp, String unit){
        if((unit.equals("F"))||(unit.equals("f"))){
        double c= (temp - 32) / 1.8;
        JOptionPane.showMessageDialog(null,c+" Celsius");
        }

         else if((unit.equals("C"))||(unit.equals("c"))){
        double f=((9.0 / 5.0) * temp) + 32.0;
   }

} }

Upvotes: 1

Jim
Jim

Reputation: 22656

One thing you can do is split the logic which converts temperature i.e.:

public static double toDegreesCelsuis(double tempF){
    double c= (tempF - 32) / 1.8;
    return c;
}  
public static double toFahrenheit(double tempC){
    double f=((9.0 / 5.0) * tempC) + 32.0;
    return f;
}

These can then be called in your main method like:

double c = Converter.toDegreesCelsuis(40.0);

Upvotes: 1

Thomas
Thomas

Reputation: 88707

You could create static methods to convert from on to another, e.g.

public static double fahrenheitToCelsius(double temp) {
 return (temp - 32) / 1.8;  
}

etc.

A side note: you could simplify your if clause to if(unit.equalsIgnoreCase("F")) or better if("F".equalsIgnoreCase(unit)), since that would handle unit = null as well.

Upvotes: 1

Related Questions