sono2424 sono2424 - 7 months ago 7
Java Question

Why doesn't my temperature conversion calculate correctly?

I am trying to take my Temperature in Fahrenheit and convert it to Celsius. When I call my

toCelsius()
method it calculates the Temperature to 0 degrees celsius.

Here is my conversion method

public Temperature toCelsius()
{
Temperature answer = new Temperature();
switch(tempType)
{
case 'C':
answer = new Temperature(this.temp,'C');
return answer;
case 'F':
answer = new Temperature(((this.temp-32)*(5/9)),'C');
return answer;

case 'K':
answer = new Temperature((this.temp-241.15),'C');
return answer;

default:
System.out.println("ERROR!");
break;

}
return answer;
}


Here is my demo

public class TempDemo {
public static void main(String[] args) {
Temperature temp1 = new Temperature(122, 'F');
System.out.println(temp1.toCelsius());
}
}

Answer

5 and 9 are int literals, so dividing them will be done using integer division - i.e., it will take only the whole part of the division. Since 5 is smaller than 9, this will result in 0, and thus so would the entire multiplication.

Instead, you should use double literals:

answer =  new Temperature(((this.temp-32)*(5.0/9.0)), 'C');
Comments