Create a class called Degree in java . The class has 3 variables, celsius, fahre
ID: 3539848 • Letter: C
Question
Create a class called Degree in java . The class has 3 variables, celsius, fahrenheit, and scale. The first two are of type double and the 3rd is a String. Create 1 constructor method, that takes in 2 parameters, one of type double and the other of type String. If the String value is Fahrenheit or Celsius, set the variable scale to that value and set the matching double variable to the value passed as a parameter. Then call method convert from the constructor. Method convert will calculate the corresponding temperature value in the other degree scale and set the remaining variable to that value. If the String passed to the constructor is neither fahrenheit or celsius, output an appropriate error message and don%u2019t do anything else. (use method equal or equalIgnoreCase of class string)
The formulas for converting are:
F= 1.8*C + 32
C = (F-32)/1.8
Explanation / Answer
public class Degree {
double celsius;
double fahrenheit;
String scale;
public Degree (double celsius, double fahrenheit, String scale)
{
if (scale.equals("Celsius"))
{
this.celsius = celsius;
this.scale=scale;
}
else if (scale.equals("Fahrenheit"))
{
this.fahrenheit =fahrenheit;
this.scale=scale;
}
else
System.out.println("Invalid scale");
}
public double convert()
{
double covertedValue=0.0;
if (scale.equals("Celsius"))
{
fahrenheit = 1.8 * celsius + 32;
covertedValue = fahrenheit;
}
else if (scale.equals("Fahrenheit"))
{
celsius = (fahrenheit-32)/1.8;
covertedValue = celsius;
}
return covertedValue;
}
public static void main(String []args){
Degree d1=new Degree(36,0,"Celsius");
System.out.println(d1.convert());
Degree d2=new Degree(0,96,"Fahrenheit");
System.out.println(d2.convert());
Degree d3=new Degree(36,0,"Wrong");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.