Applied Programming/Functions/Java

From Wikiversity
Jump to navigation Jump to search

functions.java[edit | edit source]

/** 
 * This program converts a Fahrenheit temperature to Celsius.
 * 
 * Input:
 *     Fahrenheit temperature
 * 
 * Output:
 *     Fahrenheit temperature
 *     Celsius temperature
 * 
 * Example:
 *     Enter Fahrenheit temperature:
 *      100
 *     100.0° Fahrenheit is 37.8° Celsius
 * 
 * References:
 *     * http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
 *     * https://www.w3resource.com/slides/java-coding-style-guide.php
 *     * https://en.wikipedia.org/wiki/Javadoc
 *     * http://www.mathsisfun.com/temperature-conversion.html
 */

import java.util.Scanner;

/**
 * Runs main program logic.
 */
class Main {
    public static final int TEMPERATURE_DIFFERENCE = 32;
    public static final double TEMPERATURE_RATIO = 5.0 / 9;

    public static void main(String[] args) {
        double fahrenheit = getFahrenheit();
        double celsius = fahrenheitToCelsius(fahrenheit);
        displayResults(fahrenheit, celsius);
    }
    
    /**
     * Gets Fahrenheit temperature.
     * 
     * @return  Fahrenheit temperature
    */
    private static double getFahrenheit() {
        System.out.println("Enter Fahrenheit temperature:");
        Scanner scanner = new Scanner(System.in);
        double fahrenheit;
        fahrenheit = scanner.nextDouble();
        return fahrenheit;
    }
    
    /**
     * Converts Fahrenheit temperature to Celsius.
     * 
     * @param   Fahrenheit temperature
     * @return  Celsius temperature
    */
    private static double fahrenheitToCelsius(double fahrenheit) {
        double celsius;
        celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO;
        return celsius;
    }
    
    /**
     * Displays Fahrenheit and Celsius temperatures.
     * 
     * @param   Fahrenheit temperature
     * @param   Celsius temperature
    */
    private static void displayResults(double fahrenheit, double celsius) {
        System.out.println(String.format(
            "%1$.1f° Fahrenheit is %2$.1f° Celsius",
            fahrenheit,
            celsius));
    }
}

Try It[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.

See Also[edit | edit source]