2

I am attempting to run a program through my main() class in my CelsiusToFahrenheit.java file. I created a public class called CelsiusToFahrenheit and when the class receives a parameter of the type "double" it is supposed to take that input and run it through an algorithm that converts the Celsius number in to Fahrenheit. When I compile the code and input an integer the output doesn't reflect the algorithm assigned to tempOutput. Here is the code:

import java.util.Scanner;

public class CelsiusToFahrenheit {
   public static double convertCelsiusToFahrenheit(double tempInput) {
      double tempOutput = 0.0;
      tempOutput = (tempInput * (9 / 5)) + 32;
      return tempOutput;
}


   public static void main (String [] args) {
      Scanner scnr = new Scanner(System.in);
      double tempF = 0.0;
      double tempC = 0.0;

      System.out.println("Enter temperature in Celsius: ");
      tempC = scnr.nextDouble();

      tempF = convertCelsiusToFahrenheit(tempC);

      System.out.print("Fahrenheit: ");
      System.out.println(tempF);

      scnr.close();

      return;
   }
}

Any given number I input for the tempC variable outputs tempC + 32 when it is supposed to multiply tempC by 1.8 and then add 32 to it. Where did I go wrong here?

xenteros
  • 14,275
  • 12
  • 47
  • 81
Darien Springer
  • 413
  • 6
  • 14

1 Answers1

3

tempOutput = (tempInput * (9 / 5)) + 32; - 9/5=1 because it's integer division. You can use 9/5.0 or (tempInput * 9 / 5) + 32; for using float division. The second way will work, because java is left to right and double*int will be a double, and double/int will use float division.

I'll also add a remark, that your class should be probably called TemperatureConverter instead of CelsiusToFahrenheit. Why? Because your current name closes you to the improvements. You shouldn't implement farenheitToCelsius in this class which you might want to do in the future.

xenteros
  • 14,275
  • 12
  • 47
  • 81
  • 1
    Or remove the `(` `)` will do it to. The operation `double * int / int ` will be ok. PS : I had added an answer on the duplicate yesterday using JLS reference to explain how this work. Still need some hint to improve this I think. – AxelH Jan 25 '17 at 06:38