Celsius to Fahrenheit conversion — Java

Hello I’m pretty new to Java, so I’m still getting familiar with it. Right now I’m doing a lab for class and I’ve got it mostly figured out, but there’s a section in which we are required to convert Celsius to Fahrenheit. I’m a bit stumped because we’re required to keep the first conversion as an int data type.

In our lab we have test classes, and according to the test class the first conversion (the int data type) inputs -40 degrees Celsius, runs the conversion method, and should get the result of -40 degrees Fahrenheit.

This is actually a user-defined class called Conversion that I’m writing.

Here’s the snippet I’m working with right now:

public static int celsiusToFahrenheit(int temp)
    return (temp * (9/5)) + 32;

public static double celsiusToFahrenheit(double temp)
    return (temp * (9.0/5.0)) + 32.0;

the second part works fine, inputting 12.5 degrees Celsius and returning 54.5 degrees Fahrenheit.

As I mentioned I’m still pretty new to Java so if there’s anything else you need from me please let me know.

Question I’m asking, sorry — Any ideas on how I can write the return statement so that it gives the correct conversion?

Edit: I’ve corrected it. I realized that the ints would give me a rounded value, but I wasn’t sure how to get around it. I got it into my mind that I couldn’t type cast here so I didn’t even try to explicitly cast it back to int. All is well now:

public static int celsiusToFahrenheit(int temp)
    return (int) ((temp * (9.0/5.0)) + 32);


Here’s a solution that doesn’t use type casting.
9/5 in the first method is integer division, resulting in

-40 * 1 + 32 = 8

Rewrite the return expression as (temp * 9 / 5 ) + 32 (remove the parentheses around 9/5. This will force temp * 9 first and then division by 5 after.

Leave a Reply

Your email address will not be published. Required fields are marked *