【问题标题】:My temp conversion program我的临时转换程序
【发布时间】:2014-07-24 12:05:15
【问题描述】:

我不确定为什么我的程序无法运行。有人告诉我,我不应该将 getCelcius 放在构造函数中,但现在我被卡住了。有什么帮助吗?我可能还有一些对程序没用的不需要的大括号。

import java.io.*;
class Temperature {
    //Assign varriables to int
    int factorC, factorF;
    int celcius, ferenheit;

    { 
        int getFactorC() { // Celsius
            return factorC;
        }
    }

    // declaring variables
    Temperature(int factorC, int factorF, int celcius, int ferenheit) {  
        setFactorC() {
            factorC = (9 / 5) * celcius + 32; //Calculate Celcius
        }
        {
            int getFactorF() { // Fahrenheit
                return factorF;
        }
    }

    {
        setFactorF() {
            factorF= (5 / 9) * ferenheit - 32; //Calculate Ferenheit
        }
    }
}
} //???

class TempConversion
{

【问题讨论】:

  • 请格式化您的代码!
  • 这是 Java,不是 Lisp。清理那些大括号。
  • “我也可能有一些不需要的牙套”你为什么还要把它们放在那儿?
  • 废弃你的整个程序。从最基本的 Java 教程从头开始。
  • 您还需要阅读 int 除法,因为 5 / 9 总是返回 0。您想使用 5.0 / 9.0 进行双除法。很抱歉直言不讳,但看起来你是在猜测这个,就像你在尝试学习如何编码而不先学习你的书和课程材料一样。你会想在这项必要的研究上付出更多的努力,要么放弃这门课程。

标签: java


【解决方案1】:

你的代码有很多问题,但我要做的第一件事是格式化它:

class Temperature {

    //Assign varriables to int
    int factorC, factorF;
    int celcius, ferenheit;

    int getFactorC() { // Celsius
        return factorC;
    }

    Temperature(int factorC, int factorF, int celcius, int ferenheit) {
        this.factorC = factorC;
        this.factorF = factorF;
        this.celcius = celcius;
        this.ferenheit = ferenheit;
    }

    void setFactorC() {
        factorC = (9 / 5) * celcius + 32; //Calculate Celcius
    }

    int getFactorF() { // Fahrenheit
        return factorF;
    }

    void setFactorF() {
        factorF = (5 / 9) * ferenheit - 32; //Calculate Ferenheit
    }
}

快速提示:

  • 9/5 是 1,5/9 是 0。在 Java 中,当你将整数相除时,你会得到一个整数。您可以将其替换为 9.0/5.05.0/9.0

【讨论】:

    猜你喜欢
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2019-06-27
    • 2023-03-20
    • 2020-07-12
    • 1970-01-01
    • 2012-04-01
    相关资源
    最近更新 更多