I have to write a class called temperature and my only problem is when i try to call the conversion method. Whenever I run the main program, the conversion output is 0.0
Does it have something to do with using a private variable?
Code is below.
Many thanks!
public class Temperature {
private double temp;
private String scale;
public Temperature(double temp) {
this.temp = temp;
}
public String toString () {
return "your temp is " + this.temp;
}
public double getTemp() {
return this.temp;
}
public String getScale(String scale) {
this.scale = scale;
return this.scale;
}
public double conversion() {
double temp = 0;
if (this.scale == "fahrenheit") {
temp = (this.temp - 32) * (double)(5/9);
}
else if (this.scale == "celsius") {
temp = (this.temp * (double)(9/5)) + 32;
}
return temp;
}
public boolean aboveBoiling(double temp) {
if (this.scale == "fahrenheit") {
return temp >= 212;
}
else if (this.scale == "celsius") {
return temp >= 100;
}
return true;
}
}
below is my test driver to test function calls
import java.util.*;
public class testdriver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Temperature userTemp;
String userScale;
//userTemp = new Temperature(1.0);
System.out.print("Please enter your temp scale(fahrenheit or celius): ");
userScale = sc.next();
System.out.println();
System.out.print("Please enter your temp in " + userScale + ": ");
userTemp = new Temperature(sc.nextDouble());
System.out.println();
System.out.println(userTemp.toString());
System.out.println();
System.out.println("your temp is: " + userTemp.getTemp());
System.out.println();
System.out.println("your scale is: " + userTemp.getScale(userScale));
System.out.println();
System.out.println(userTemp.conversion());
System.out.println();
double userTemp2 = userTemp.conversion();
System.out.println(userTemp.aboveBoiling(userTemp2));
}
}
Replace this.scale == "fahrenheit"
and this.scale == "celcius"
by this.scale.equals("fahrenheit")
and this.scale.equals("celcius").
In java, the == operator compare only references or primitive values (int, long, float, double...).
Edit: I found another problem in your code:
(this.temp - 32) * (double)(5/9);
5 and 9 are integers, then the division will result in 0. You need to cast one of the operands to double, before the / operation:
(this.temp - 32) * ((double)5/9);
or:
(this.temp - 32) * (5./9.);