Вопрос

i am having problems with a java program, a Java E6B Flight Computer, suddenly it stopped converting Fahrenheit to Celsius, it always outputs 0, no matter what value, Celsius to Fahrenheit is written similar and works fine, both functions write to a log file, and this works, except the Fahrenheit to Celsius comes up as 0 for any input in the log file. (i am aware i misspelled Fahrenheit). i have considered changing to a Double instead of floats

here is the code of the two functions. also included is the rounding function.

public static String celstofare(String Celsius){

    // function level
    float a;
    // if user types string, returns error
    try
    {
        a = Float.parseFloat(Celsius);
                    float math = ((a * (9/5)) + 32);
                    String out = round(math, 2) +"";
                    // log file update mechanism
                            File file = new File("log.txt");
                            FileWriter writer;
                            try {
                                writer = new FileWriter(file, true);
                                PrintWriter printer = new PrintWriter(writer);
                                Date date = new Date();
                                String strDate = date.toString();
                                printer.println("Converted Celsius to Farenheit  on: " + strDate);
                                printer.println("Celsius: " + a + "Farenheit: " + out);
                                printer.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
        return out;
    }
    catch (Exception e)
    {
        return "error";
    }

}

    public static String faretocels(String Farenheit){

    // function level
    float a;
    // if user types string, returns error
    try
    {
        a = Float.parseFloat(Farenheit);
                    float math = ((a - 32) * (5/9));
                    String out = round(math, 2) +"";
                    // log file update mechanism
                            File file = new File("log.txt");
                            FileWriter writer;
                            try {
                                writer = new FileWriter(file, true);
                                PrintWriter printer = new PrintWriter(writer);
                                Date date = new Date();
                                String strDate = date.toString();
                                printer.println("Converted Farenheit to Celsius on: " + strDate);
                                printer.println("Farenheit: " + a + "Celsius: " + out);
                                printer.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
        return out;
    }
    catch (Exception e)
    {
        return "error";
    }

}
    public static BigDecimal round(double d, int decimalPlace) {
    BigDecimal bd = new BigDecimal(Double.toString(d));
    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);       
    return bd;
}

here is the function and action listener that calls it, every thing else works, and i have verified the proper inputs and outputs are set up. the input and output boxes are JTextFields

        else if (e.getSource() == btnCalculateConversion){
                    mphOut.setText(Conversions.KnotstoMph(knots.getText()));
                    knotsOut.setText(Conversions.mphtoknots(mph.getText()));
                    nmout.setText(Conversions.mphtoknots(mph.getText()));
                    miout.setText(Conversions.KnotstoMph(knots.getText()));
                    poundsout.setText(Conversions.galtopound(gal.getText()));
                    galout.setText(Conversions.poundtogal(pounds.getText()));
                    tempfout.setText(Conversions.celstofare(tempc.getText()));
                    tempcout.setText(Conversions.faretocels(tempf.getText()));
Это было полезно?

Решение

All the answers are very good, but I'll add one more thing since you're a student:

That method should do one thing and only one thing: convert temperature from Farenheit to Celcius. That's it. No writing to files or anything else. Do that outside the method.

Why on earth are you passing Strings in and out? Temperatures are numbers; use them.

Learn the Sun Java coding standards. Variable names start with lower case letters, class names with upper case.

So your method should look like this:

public class TemperatureConverter {

    private TemperatureConverter() {}

    public static double celciusToFarenheit(double celcius) {
        return 1.8*celcius + 32.0;    
    }

    public static double farenheitToCelcius(double farenheit) {
        return (farenheit - 32.0)/1.8;
    }
}

Другие советы

float math = ((a * (9/5)) + 32);

9/5 is being evaluated as integer division, or 1. a * 9 / 5 would avoid this problem, since evaluation is left-to-right.

The strange part is that this should result in a temperature of a + 32 every time, rather than 0. So the likely implication is that Celsius is being evaluated in parseFloat as 0. Have you tried stepping through a debugger, to see what the value of a is?

Because when you do the 5/9 division part when converting from Fahrenheit to Celsius, Java thinks it is purely integer division and will round down to zero and then assumes you are multiplying by zero after subtracting 32 from your original temperature.

The solution is to force Java to do floating point division and this can be accomplished by doing something like 5.0/9, 5/9.0, or even 5.0/9.0 . Then Java will make sure that no rounding to zero will take place and your answer will not be zero, unless it needs to be.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top