Computer Programming/Functions/Java

From Wikiversity
Jump to navigation Jump to search

subroutines.java[edit]

// This program asks the user for a Fahrenheit temperature, 
// converts the given temperature to Celsius,
// and displays the results.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/Java_Programming

import java.util.*;

class subroutines {
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        double f;
        double c;
        
        f = getF();
        c = calculateC(f);
        displayResult(f, c);
    }

    private static double getF() {
        double f;
        
        System.out.println("Enter Fahrenheit temperature:");
        f = input.nextDouble();
        
        return f;
    }

    private static double calculateC(double f) {
        double c;
        
        c = (f - 32) * 5 / 9;
        
        return c;
    }

    private static void displayResult(double f, double c) {
        System.out.println(f + "° Fahrenheit is " + c + "° Celsius");
    }
}

Try It[edit]

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]