Friday, May 31, 2024

Temperature Converter Using Abstraction in Java

 


Program Listing

import java.text.DecimalFormat;


public class Main {

    private double temperature;

    private DecimalFormat decimalFormat = new DecimalFormat("#.00");


    public Main() {

        // Default constructor

    }


    // Method to set the temperature in Fahrenheit

    public void setTemperatureInFahrenheit(double fahrenheit) {

        this.temperature = fahrenheit;

    }


    // Method to set the temperature in Celsius

    public void setTemperatureInCelsius(double celsius) {

        // Convert Celsius to Fahrenheit

        this.temperature = celsiusToFahrenheit(celsius);

    }


    // Method to convert the temperature to Fahrenheit with two decimal places

    public String getTemperatureInFahrenheit() {

        return decimalFormat.format(temperature) + " Degree's Fahrenheit";

    }


    // Method to convert the temperature to Celsius with two decimal places

    public String getTemperatureInCelsius() {

        return decimalFormat.format(fahrenheitToCelsius(temperature)) + " Degree's Celsius";

    }


    // Helper method to convert Celsius to Fahrenheit

    private double celsiusToFahrenheit(double celsius) {

        return (celsius * 9/5) + 32;

    }


    // Helper method to convert Fahrenheit to Celsius

    private double fahrenheitToCelsius(double fahrenheit) {

        return (fahrenheit - 32) * 5/9;

    }


    public static void main(String[] args) {

        Main converter = new Main();


        converter.setTemperatureInFahrenheit(120.84);

        

        System.out.println("\n\tTemperature Converter Using Abstraction in Java\n ");

        System.out.println("\tTemperature in Fahrenheit: " + converter.getTemperatureInFahrenheit()+ "\n");

        System.out.println("\tTemperature in Celsius: " + converter.getTemperatureInCelsius());

        System.out.println("\n\n\tEnd of Program. Thank you for using this program \n ");

        

    }

}


No comments:

Post a Comment