Programming language is JAVA: We want to implement a Temperature class that stor
ID: 3830771 • Letter: P
Question
Programming language is JAVA:
We want to implement a Temperature class that stores the temperature using a private instance variable of type double and includes public methods getFahrenheit(), setFahrenheit(), getCelsius() and setCelsius() methods to access and modify the temperature. The class will supply a no parameter constructor that sets the temperature to 0.0 celsius = 32.0 fahrenheit.
a) Does it matter to the client how we store the temperature internally (as Celsius or Fahrenheit)? If so, how so? If not why not?
b) Implement the class using one of the two choices for the internal temperature scale.
Explanation / Answer
a) Does it matter to the client how we store the temperature internally (as Celsius or Fahrenheit)? If so, how so? If not why not?
It doesn't matter to client. He can always get either of those values using accessors.
b) Implement the class using one of the two choices for the internal temperature scale.
import java.util.Scanner;
public class Temp
{
// No additional members of the class
// Feel free to use local variables as necessary in each method
private double tValue;
// If you like, you can change the type of scale to Character
private char scale;
// For use in set()
private Scanner vScan = new Scanner(System.in);
// The default constructor for the class
public Temp()
{
tValue = 32;
scale = 'F';
}
// The parameterized constructor for the class
public Temp(double initT, char initS)
{
this.tValue = initT;
this.scale = initS;
if (initS != 'c' || initS != 'C')
this.scale = 'F';
}
// Input values for the instance variables using the Scanner vScan
public void set()
{
System.out.println("Enter value for temperature: ");
tValue = vScan.nextDouble();
while(true)
{
System.out.println("Enter a value for scale (either of c, C, f, F: ");
char c = vScan.next().charAt(0);
if (c != 'f' || c != 'F' || c!= 'c' || c!= 'C')
{
System.out.println("Please try again by entering correct value for scale.");
}
else
{
this.scale = c;
break;
}
}
}
// Return the temperature in Celsius
public double getC()
{
if (scale == 'c' || scale == 'C')
{
return this.tValue;
}
return (this.tValue - 32)/1.8;
}
// Return the temperature in Fahrenheit
public double getF()
{
if (scale == 'f' || scale == 'F')
{
return this.tValue;
}
return (this.tValue*1.8) + 32;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.