1

This is a strange issue:

So when I choose 1 for Farenheit it will prompt me to enter the Farenheit value.

It will then go the FarenHeitToCelcius method. For some reason the celcius is always returning 0.0

Any kind of help would be greatly appreciated

package Exercises;
import java.util.Scanner;

public class TemperatureCOnversion {

  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);
    System.out.println("Enter 1 to return Celcius or 2 for Farenheit: ");
    System.out.println("Your CHOICE: ");
    int choice = input.nextInt();
     switch(choice){

     case 1:
        System.out.println("Enter the Fareheit for celcius calculation: ");
        double farenheit = input.nextDouble();
        System.out.println(farenheit);
        double celcius_result = FarenHeitToCelcius(farenheit);
        System.out.println(celcius_result);
        break;
     case 2:
         System.out.println("Enter the Celcius for Farenheit calculation: ");
            double celcius1 = input.nextDouble();
            double farenheit_result = CelciusToFarenheit(celcius1);
            break;
     default:
         System.out.println(" **********Invalid Entry ******");
         break;


     }

  }

  public static double FarenHeitToCelcius(double f){
    //double celcius = 0;
    double celcius = (5/9)*(f -32);
    System.out.println(" The equivalent celcius temperature is: " + celcius);
    return celcius;

  }

  public static double CelciusToFarenheit(double c){
    double farenheit =( (9/5*c) + 32);
    System.out.println(" The equivalent fareheit temperature is: " + farenheit);
    return farenheit;
  }


}
vefthym
  • 7,108
  • 5
  • 26
  • 55
Nabeel A.Rahman
  • 171
  • 3
  • 14

3 Answers3

4

5/9 will do integer division, which returns 0. You need to cast one of these integers to double, like

double celcius = ((double)5/9)*(f -32);

or

double celcius = (5.0/9)*(f -32);    

This will first convert 5 to a double, and then divide this double to 9, which gives the correct result of the division.

In the CelciusToFarenheit method, there is no problem, since, in the line:

double farenheit =( (9/5*c) + 32);

9/5*c is evaluated as 9/(5*c), where c is a double, so 5*c first returns a double and then 9 is divided to this double. So there is no integer division there.

vefthym
  • 7,108
  • 5
  • 26
  • 55
1

I think (5/9) results 0 (both numbers are integer – result is integer), replace it with (5.0 / 9.0) or (5d / 9d).

0

The Problem lies in this line:

double celcius = (5/9)*(f -32);

5/9 will be interpreted as int 5 /int 9 - it will always return 0 since 9 does fit in 5 0 times.

since you want to operate with double, this would work:

double celcius = (5.0 / 9.0) * (f - 32);
Rhayene
  • 565
  • 6
  • 18