8.6: Java Examples
- Page ID
- 10715
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
Objects
// This program creates instances of the Temperature class to convert Celsius // and Fahrenheit temperatures. // // References: // https://www.mathsisfun.com/temperature-conversion.html // https://en.wikibooks.org/wiki/Java_Programming import java.util.*; class Main { public static void main(String[] args) { Temperature temp1 = new Temperature(); temp1.setCelsius(100.0); System.out.println("temp1.celsius = " + temp1.getCelsius().toString()); System.out.println("temp1.fahrenheit = " + temp1.getFahrenheit().toString()); System.out.println(""); Temperature temp2 = new Temperature(); temp2.setFahrenheit(100.0); System.out.println("temp2.fahrenheit = " + temp2.getFahrenheit().toString()); System.out.println("temp2.celsius = " + temp2.getCelsius().toString()); } } // This class converts temperature between Celsius and Fahrenheit. // It may be used by assigning a value to either Celsius or Fahrenheit // and then retrieving the other value, or by calling the ToCelsius or // ToFahrenheit methods directly. class Temperature { Double celsius; Double fahrenheit; public Double getCelsius() { return celsius; } public void setCelsius(Double value) { celsius = value; fahrenheit = toFahrenheit(celsius); } public Double getFahrenheit() { return fahrenheit; } public void setFahrenheit(Double value) { fahrenheit = value; celsius = toCelsius(fahrenheit); } public Double toCelsius(Double fahrenheit) { return (fahrenheit - 32) * 5 / 9; } public Double toFahrenheit(Double celsius) { return celsius * 9 / 5 + 32; } }
Output
temp1.celsius = 100.0 temp1.fahrenheit = 212.0 temp2.fahrenheit = 100.0 temp2.celsius = 37.77777777777778
References
- Wikiversity: Computer Programming