Object-Oriented Programming/Methods/Java
Appearance
Main.java
[edit | edit source]// This program demonstrates use of the Temperature class.
//
// References:
// * http://www.mathsisfun.com/temperature-conversion.html
class Main {
public static void main(String[] args) {
var temperature = new Temperature();
System.out.println(temperature.toCelsius(98.6));
System.out.println(temperature.toFahrenheit(37));
}
}
Temperature.java
[edit | edit source]// Temperature converter. Provides temperature conversion functions. Supports Fahrenheit and Celius temperatures.
//
// Examples:
// var temperature = new Temperature();
// System.out.println(temperature.toCelsius(98.6));
// System.out.println(temperature.toFahrenheit(37));
//
// References:
// * http://www.mathsisfun.com/temperature-conversion.html
class Temperature {
// Converts Fahrenheit temperature to Celsius.
public double toCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
// Converts Celsius temperature to Fahrenheit.
public double toFahrenheit(double celsius) {
return celsius * 9 / 5 + 32;
}
}
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.