basic java temperature converter

user2450335 picture user2450335 · Jun 10, 2013 · Viewed 23.6k times · Source

So I am trying to write a program to convert degrees C to F or vice versa. Every time I run the program I am getting mistakes which I can't readily explain. For instance, it converts 100 C to 132 F. It converts 212 F to 0 C. My conversion formulas are right. Can anyone give me some clues? I tried declaring the floats in the class outside the main, but it didn't help.

import java.util.Scanner;
public class TempConverter{
public static void main(String [] args)
{
    float f, c;
    f = c = 0;
    int a;
    Scanner scan = new Scanner (System.in);
    System.out.println("Press 1 for C->F or 2 for F->C");
    a = scan.nextInt();
    if (a == 1) 
        convertCtoFAndPrint();
    else
        convertFtoCAndPrint();
}

public static void convertFtoCAndPrint()
{
    f = c = 0;
    Scanner scan = new Scanner (System.in);
    System.out.println("Please enter degrees F");
    f = scan.nextFloat();
    c = (5/9)*(f-32);
    System.out.println(f + " degrees F is " + c + " degrees C.");
}

public static void convertCtoFAndPrint()
{
    Scanner scan = new Scanner (System.in);
    System.out.println("Please enter degrees C");
    c = scan.nextFloat();
    f = c*(9/5)+32;
    System.out.println(c + " degrees C is " + f + " degrees F.");
}

}

Answer

fge picture fge · Jun 10, 2013

You write:

c = (5/9)*(f-32);

But c is a float.

The problem is that 5 / 9 is an integer division, whose result is always 0.

Similarly:

f = c*(9/5)+32;

here 9 / 5 will always be 1. And c will be cast to an int.

You need to write 5.0, 9.0 etc.